repo stringclasses 1 value | instance_id stringlengths 22 24 | problem_statement stringlengths 30 24.1k | patch stringlengths 0 1.9M | test_patch stringclasses 1 value | created_at stringdate 2022-11-25 05:12:07 2025-06-13 10:24:29 | hints_text stringlengths 0 234k | base_commit stringlengths 40 40 | test_instructions stringlengths 0 232k | filenames listlengths 0 300 |
|---|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | juspay__hyperswitch-4674 | Bug: Add audit events for CompleteAuthorize update
Created from #4525
This covers adding events for Complete Authorize operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 850fa738cd8..8c003f54adf 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -16,6 +16,7 @@ use crate::{
PaymentData,
},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -462,7 +463,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -492,6 +493,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ req_state
+ .event_context
+ .event(AuditEvent::new(AuditEventType::PaymentCompleteAuthorize))
+ .with(payment_data.to_event())
+ .emit();
+
payment_data.payment_intent = updated_payment_intent;
Ok((Box::new(self), payment_data))
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 5f2ed10bc5f..c314fa8409f 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -33,6 +33,7 @@ pub enum AuditEventType {
},
PaymentApprove,
PaymentCreate,
+ PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
error_message: Option<String>,
@@ -78,6 +79,7 @@ impl Event for AuditEvent {
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
+ AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
| 2024-10-14T13:49:41Z |
## Description
Created from #4674
This covers adding events for `CompleteAuthorize` operation
## How did you test it
Use `globalpay` as connector, `wallet` as payment_method and `paypal` as payment_method_type
```bash
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
}
```
Create a payment:
```bash
{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 600,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_redirect":{}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Response:
```json
{
"payment_id": "pay_AkkvFG6dZN3gasgy729h",
"merchant_id": "postman_merchant_GHAction_93d97914-663d-4099-b4a2-a9ec314d654e",
"status": "requires_customer_action",
"amount": 600,
"net_amount": 600,
"amount_capturable": 600,
"amount_received": null,
"connector": "globalpay",
"client_secret": "pay_AkkvFG6dZN3gasgy729h_secret_XLheDrFzLzXL7eF0BOxV",
"created": "2024-11-06T14:35:59.773Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "DE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_AkkvFG6dZN3gasgy729h/postman_merchant_GHAction_93d97914-663d-4099-b4a2-a9ec314d654e/pay_AkkvFG6dZN3gasgy729h_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1730903759,
"expires": 1730907359,
"secret": "epk_2f5f6461495c44d5836e790820a006f4"
},
"manual_retry_allowed": null,
"connector_transaction_id": "TRN_N8FIKEvvsrYO5xqzUcwgzTLg9dXnCq_3gasgy729h_1",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_AkkvFG6dZN3gasgy729h_1",
"payment_link": null,
"profile_id": "pro_S5r08g7HrBg5FT2NWS3l",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_8uJfYpthurOSVoLJwxfR",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-11-06T14:50:59.773Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-06T14:36:02.437Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Hit the `redirction_url` and complete the payment.
Audit logs will get generated and can be viewed in `hyperswitch-audit-events` topic in kafka with `PaymentCompleteAuthorize` event-type.
<img width="1361" alt="image" src="https://github.com/user-attachments/assets/aa909b5b-7eb8-4f03-8453-8c02af9aa74d"> | 535c8d4e6fc8226a66ba2c45bb8102625454306c | [
"crates/router/src/core/payments/operations/payment_complete_authorize.rs",
"crates/router/src/events/audit_events.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6307 | Bug: [FEATURE] Set header consumption as optional in Open banking flows
### Feature Description
Set header consumption as optional in Open banking flows
### Possible Implementation
Set header consumption as optional in Open banking flows
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs
index 443a4c30394..8ed52907da8 100644
--- a/crates/api_models/src/pm_auth.rs
+++ b/crates/api_models/src/pm_auth.rs
@@ -4,8 +4,6 @@ use common_utils::{
id_type, impl_api_event_type,
};
-use crate::enums as api_enums;
-
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct LinkTokenCreateRequest {
@@ -14,9 +12,6 @@ pub struct LinkTokenCreateRequest {
pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch
pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector
pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector
- pub client_platform: api_enums::ClientPlatform, // Client Platform to perform platform based processing
- pub android_package_name: Option<String>, // Android Package name to be sent for Android platform
- pub redirect_uri: Option<String>, // Merchant redirect_uri to be sent in case of IOS platform
}
#[derive(Debug, Clone, serde::Serialize)]
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
index af0c26a5b85..a91aa57a1e4 100644
--- a/crates/pm_auth/src/connector/plaid/transformers.rs
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -45,28 +45,20 @@ impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
)?,
},
android_package_name: match item.request.client_platform {
- api_models::enums::ClientPlatform::Android => {
- Some(item.request.android_package_name.clone().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "android_package_name",
- },
- )?)
+ Some(api_models::enums::ClientPlatform::Android) => {
+ item.request.android_package_name.clone()
}
- api_models::enums::ClientPlatform::Ios
- | api_models::enums::ClientPlatform::Web
- | api_models::enums::ClientPlatform::Unknown => None,
+ Some(api_models::enums::ClientPlatform::Ios)
+ | Some(api_models::enums::ClientPlatform::Web)
+ | Some(api_models::enums::ClientPlatform::Unknown)
+ | None => None,
},
redirect_uri: match item.request.client_platform {
- api_models::enums::ClientPlatform::Ios => {
- Some(item.request.redirect_uri.clone().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "redirect_uri",
- },
- )?)
- }
- api_models::enums::ClientPlatform::Android
- | api_models::enums::ClientPlatform::Web
- | api_models::enums::ClientPlatform::Unknown => None,
+ Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(),
+ Some(api_models::enums::ClientPlatform::Android)
+ | Some(api_models::enums::ClientPlatform::Web)
+ | Some(api_models::enums::ClientPlatform::Unknown)
+ | None => None,
},
})
}
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index 878043afe50..bae9ee59848 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -25,7 +25,7 @@ pub struct LinkTokenRequest {
pub country_codes: Option<Vec<String>>,
pub language: Option<String>,
pub user_info: Option<id_type::CustomerId>,
- pub client_platform: api_enums::ClientPlatform,
+ pub client_platform: Option<api_enums::ClientPlatform>,
pub android_package_name: Option<String>,
pub redirect_uri: Option<String>,
}
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs
index c4eb5a7a035..f0cf91b9cf6 100644
--- a/crates/router/src/connector/plaid/transformers.rs
+++ b/crates/router/src/connector/plaid/transformers.rs
@@ -163,21 +163,15 @@ impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest
match item.request.payment_method_data {
domain::PaymentMethodData::OpenBanking(ref data) => match data {
domain::OpenBankingData::OpenBankingPIS { .. } => {
- let headers = item.header_payload.clone().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "header_payload",
- },
- )?;
+ let headers = item.header_payload.clone();
- let platform = headers.x_client_platform.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "x_client_platform",
- },
- )?;
+ let platform = headers
+ .as_ref()
+ .and_then(|headers| headers.x_client_platform.clone());
let (is_android, is_ios) = match platform {
- common_enums::ClientPlatform::Android => (true, false),
- common_enums::ClientPlatform::Ios => (false, true),
+ Some(common_enums::ClientPlatform::Android) => (true, false),
+ Some(common_enums::ClientPlatform::Ios) => (false, true),
_ => (false, false),
};
@@ -208,20 +202,16 @@ impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
},
android_package_name: if is_android {
- Some(headers.x_app_id.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "x-app-id",
- },
- )?)
+ headers
+ .as_ref()
+ .and_then(|headers| headers.x_app_id.clone())
} else {
None
},
redirect_uri: if is_ios {
- Some(headers.x_redirect_uri.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "x_redirect_uri",
- },
- )?)
+ headers
+ .as_ref()
+ .and_then(|headers| headers.x_redirect_uri.clone())
} else {
None
},
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index a09ca4fc6e6..a37a91a55f1 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -51,6 +51,7 @@ pub async fn create_link_token(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
payload: api_models::pm_auth::LinkTokenCreateRequest,
+ headers: Option<api_models::payments::HeaderPayload>,
) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> {
let db = &*state.store;
@@ -165,9 +166,13 @@ pub async fn create_link_token(
)?]),
language: payload.language,
user_info: payment_intent.and_then(|pi| pi.customer_id),
- client_platform: payload.client_platform,
- android_package_name: payload.android_package_name,
- redirect_uri: payload.redirect_uri,
+ client_platform: headers
+ .as_ref()
+ .and_then(|header| header.x_client_platform.clone()),
+ android_package_name: headers.as_ref().and_then(|header| header.x_app_id.clone()),
+ redirect_uri: headers
+ .as_ref()
+ .and_then(|header| header.x_redirect_uri.clone()),
},
response: Ok(pm_auth_types::LinkTokenResponse {
link_token: "".to_string(),
@@ -211,6 +216,7 @@ pub async fn create_link_token(
_merchant_account: domain::MerchantAccount,
_key_store: domain::MerchantKeyStore,
_payload: api_models::pm_auth::LinkTokenCreateRequest,
+ _headers: Option<api_models::payments::HeaderPayload>,
) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> {
todo!()
}
diff --git a/crates/router/src/routes/pm_auth.rs b/crates/router/src/routes/pm_auth.rs
index e0cce9c515c..cc0ab02b556 100644
--- a/crates/router/src/routes/pm_auth.rs
+++ b/crates/router/src/routes/pm_auth.rs
@@ -2,7 +2,9 @@ use actix_web::{web, HttpRequest, Responder};
use api_models as api_types;
use router_env::{instrument, tracing, types::Flow};
-use crate::{core::api_locking, routes::AppState, services::api as oss_api};
+use crate::{
+ core::api_locking, routes::AppState, services::api, types::transformers::ForeignTryFrom,
+};
#[instrument(skip_all, fields(flow = ?Flow::PmAuthLinkTokenCreate))]
pub async fn link_token_create(
@@ -17,9 +19,17 @@ pub async fn link_token_create(
&payload,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
- Err(e) => return oss_api::log_and_return_error_response(e),
+ Err(e) => return api::log_and_return_error_response(e),
};
- Box::pin(oss_api::server_wrap(
+
+ let header_payload = match api_types::payments::HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => {
+ return api::log_and_return_error_response(err);
+ }
+ };
+
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -30,6 +40,7 @@ pub async fn link_token_create(
auth.merchant_account,
auth.key_store,
payload,
+ Some(header_payload.clone()),
)
},
&*auth,
@@ -51,9 +62,9 @@ pub async fn exchange_token(
&payload,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
- Err(e) => return oss_api::log_and_return_error_response(e),
+ Err(e) => return api::log_and_return_error_response(e),
};
- Box::pin(oss_api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
| 2024-10-14T09:59:58Z |
## Description
<!-- Describe your changes in detail -->
Make header data to consume in open banking flows as optional.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
Test all open banking flows (PM auth and Payment initiation)
Refer to this PR - https://github.com/juspay/hyperswitch/pull/3952 | a7c6f57668683132ac3b59a0398742ea9d12bdca |
Test all open banking flows (PM auth and Payment initiation)
Refer to this PR - https://github.com/juspay/hyperswitch/pull/3952
| [
"crates/api_models/src/pm_auth.rs",
"crates/pm_auth/src/connector/plaid/transformers.rs",
"crates/pm_auth/src/types.rs",
"crates/router/src/connector/plaid/transformers.rs",
"crates/router/src/core/pm_auth.rs",
"crates/router/src/routes/pm_auth.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6303 | Bug: [FEATURE] Enable Paze Wallet for Cybersource on Dashboard
### Feature Description
Enable Paze Wallet for Cybersource on Dashboard
### Possible Implementation
Enable Paze Wallet for Cybersource on Dashboard
### 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/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 3e81062b91e..f4523cf6171 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1213,6 +1213,8 @@ merchant_secret="Source verification key"
payment_method_type = "apple_pay"
[[cybersource.wallet]]
payment_method_type = "google_pay"
+[[cybersource.wallet]]
+ payment_method_type = "paze"
[cybersource.connector_auth.SignatureKey]
api_key="Key"
key1="Merchant ID"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 08141f88d21..80a3af60c49 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1213,6 +1213,8 @@ merchant_secret="Source verification key"
payment_method_type = "apple_pay"
[[cybersource.wallet]]
payment_method_type = "google_pay"
+[[cybersource.wallet]]
+ payment_method_type = "paze"
[cybersource.connector_auth.SignatureKey]
api_key="Key"
key1="Merchant ID"
| 2024-10-14T07:32:52Z |
## Description
<!-- Describe your changes in detail -->
Enable Paze Wallet for Cubersource on Dashboard
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6303
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Only config changes hence no testing required. | 19a8474d8731ed7149b541f02ad237e30c4c9f24 |
Only config changes hence no testing required.
| [
"crates/connector_configs/toml/development.toml",
"crates/connector_configs/toml/sandbox.toml"
] | |
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 |
## 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)?
--> | 9597215a66e38b0021bd804ffe4d9d040e30f8f9 | [
"crates/router/src/connector/rapyd/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6473 | Bug: [FEATURE] Add support for network token migration
Currently, the migration api only supports card raw details migration.
Feature description -
Add support to migrate raw network token details along with the network token requestor ref id. | diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index b1f15188dcb..6fdb7d59b0f 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -18,7 +18,7 @@ use crate::{
ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest,
PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse,
PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse,
- PaymentMethodResponse, PaymentMethodUpdate,
+ PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
self, ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints,
@@ -218,6 +218,29 @@ impl ApiEventMetric for PaymentMethodResponse {
}
}
+impl ApiEventMetric for PaymentMethodMigrateResponse {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.payment_method_response.payment_method_id.clone(),
+ payment_method: self.payment_method_response.payment_method,
+ payment_method_type: self.payment_method_response.payment_method_type,
+ })
+ }
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.payment_method_response.payment_method_id.clone(),
+ payment_method: self.payment_method_response.payment_method_type,
+ payment_method_type: self.payment_method_response.payment_method_subtype,
+ })
+ }
+}
+
impl ApiEventMetric for PaymentMethodUpdate {}
impl ApiEventMetric for DefaultPaymentMethod {
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 5baf138b090..0343ee02119 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -245,6 +245,9 @@ pub struct PaymentMethodMigrate {
/// Card Details
pub card: Option<MigrateCardDetail>,
+ /// Network token details
+ pub network_token: Option<MigrateNetworkTokenDetail>,
+
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
pub metadata: Option<pii::SecretSerdeValue>,
@@ -276,6 +279,24 @@ pub struct PaymentMethodMigrate {
pub network_transaction_id: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct PaymentMethodMigrateResponse {
+ //payment method response when payment method entry is created
+ pub payment_method_response: PaymentMethodResponse,
+
+ //card data migration status
+ pub card_migrated: Option<bool>,
+
+ //network token data migration status
+ pub network_token_migrated: Option<bool>,
+
+ //connector mandate details migration status
+ pub connector_mandate_details_migrated: Option<bool>,
+
+ //network transaction id migration status
+ pub network_transaction_id_migrated: Option<bool>,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReference(
pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
@@ -540,6 +561,53 @@ pub struct MigrateCardDetail {
pub card_type: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct MigrateNetworkTokenData {
+ /// Network Token Number
+ #[schema(value_type = String,example = "4111111145551142")]
+ pub network_token_number: CardNumber,
+
+ /// Network Token Expiry Month
+ #[schema(value_type = String,example = "10")]
+ pub network_token_exp_month: masking::Secret<String>,
+
+ /// Network Token Expiry Year
+ #[schema(value_type = String,example = "25")]
+ pub network_token_exp_year: masking::Secret<String>,
+
+ /// Card Holder Name
+ #[schema(value_type = String,example = "John Doe")]
+ pub card_holder_name: Option<masking::Secret<String>>,
+
+ /// Card Holder's Nick Name
+ #[schema(value_type = Option<String>,example = "John Doe")]
+ pub nick_name: Option<masking::Secret<String>>,
+
+ /// Card Issuing Country
+ pub card_issuing_country: Option<String>,
+
+ /// Card's Network
+ #[schema(value_type = Option<CardNetwork>)]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ /// Issuer Bank for Card
+ pub card_issuer: Option<String>,
+
+ /// Card Type
+ pub card_type: Option<String>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct MigrateNetworkTokenDetail {
+ /// Network token details
+ pub network_token_data: MigrateNetworkTokenData,
+
+ /// Network token requestor reference id
+ pub network_token_requestor_ref_id: String,
+}
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -2082,6 +2150,10 @@ pub struct PaymentMethodRecord {
pub original_transaction_amount: Option<i64>,
pub original_transaction_currency: Option<common_enums::Currency>,
pub line_number: Option<i64>,
+ pub network_token_number: Option<CardNumber>,
+ pub network_token_expiry_month: Option<masking::Secret<String>>,
+ pub network_token_expiry_year: Option<masking::Secret<String>>,
+ pub network_token_requestor_ref_id: Option<String>,
}
#[derive(Debug, Default, serde::Serialize)]
@@ -2098,6 +2170,10 @@ pub struct PaymentMethodMigrationResponse {
#[serde(skip_serializing_if = "Option::is_none")]
pub migration_error: Option<String>,
pub card_number_masked: Option<masking::Secret<String>>,
+ pub card_migrated: Option<bool>,
+ pub network_token_migrated: Option<bool>,
+ pub connector_mandate_details_migrated: Option<bool>,
+ pub network_transaction_id_migrated: Option<bool>,
}
#[derive(Debug, Default, serde::Serialize)]
@@ -2107,8 +2183,10 @@ pub enum MigrationStatus {
Failed,
}
-type PaymentMethodMigrationResponseType =
- (Result<PaymentMethodResponse, String>, PaymentMethodRecord);
+type PaymentMethodMigrationResponseType = (
+ Result<PaymentMethodMigrateResponse, String>,
+ PaymentMethodRecord,
+);
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
@@ -2117,14 +2195,18 @@ impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse
fn from((response, record): PaymentMethodMigrationResponseType) -> Self {
match response {
Ok(res) => Self {
- payment_method_id: Some(res.payment_method_id),
- payment_method: res.payment_method,
- payment_method_type: res.payment_method_type,
- customer_id: res.customer_id,
+ payment_method_id: Some(res.payment_method_response.payment_method_id),
+ payment_method: res.payment_method_response.payment_method,
+ payment_method_type: res.payment_method_response.payment_method_type,
+ customer_id: res.payment_method_response.customer_id,
migration_status: MigrationStatus::Success,
migration_error: None,
card_number_masked: Some(record.card_number_masked),
line_number: record.line_number,
+ card_migrated: res.card_migrated,
+ network_token_migrated: res.network_token_migrated,
+ connector_mandate_details_migrated: res.connector_mandate_details_migrated,
+ network_transaction_id_migrated: res.network_transaction_id_migrated,
},
Err(e) => Self {
customer_id: Some(record.customer_id),
@@ -2143,14 +2225,18 @@ impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse
fn from((response, record): PaymentMethodMigrationResponseType) -> Self {
match response {
Ok(res) => Self {
- payment_method_id: Some(res.payment_method_id),
- payment_method: res.payment_method_type,
- payment_method_type: res.payment_method_subtype,
- customer_id: Some(res.customer_id),
+ payment_method_id: Some(res.payment_method_response.payment_method_id),
+ payment_method: res.payment_method_response.payment_method_type,
+ payment_method_type: res.payment_method_response.payment_method_subtype,
+ customer_id: Some(res.payment_method_response.customer_id),
migration_status: MigrationStatus::Success,
migration_error: None,
card_number_masked: Some(record.card_number_masked),
line_number: record.line_number,
+ card_migrated: res.card_migrated,
+ network_token_migrated: res.network_token_migrated,
+ connector_mandate_details_migrated: res.connector_mandate_details_migrated,
+ network_transaction_id_migrated: res.network_transaction_id_migrated,
},
Err(e) => Self {
customer_id: Some(record.customer_id),
@@ -2213,6 +2299,22 @@ impl
card_issuing_country: None,
nick_name: Some(record.nick_name.clone()),
}),
+ network_token: Some(MigrateNetworkTokenDetail {
+ network_token_data: MigrateNetworkTokenData {
+ network_token_number: record.network_token_number.unwrap_or_default(),
+ network_token_exp_month: record.network_token_expiry_month.unwrap_or_default(),
+ network_token_exp_year: record.network_token_expiry_year.unwrap_or_default(),
+ card_holder_name: record.name,
+ nick_name: Some(record.nick_name.clone()),
+ card_issuing_country: None,
+ card_network: None,
+ card_issuer: None,
+ card_type: None,
+ },
+ network_token_requestor_ref_id: record
+ .network_token_requestor_ref_id
+ .unwrap_or_default(),
+ }),
payment_method: record.payment_method,
payment_method_type: record.payment_method_type,
payment_method_issuer: None,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index d607cd04bff..55460037855 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -248,6 +248,11 @@ pub enum PaymentMethodUpdate {
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
},
+ NetworkTokenDataUpdate {
+ network_token_requestor_reference_id: Option<String>,
+ network_token_locker_id: Option<String>,
+ network_token_payment_method_data: Option<Encryption>,
+ },
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
@@ -620,6 +625,27 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_token_locker_id: None,
network_token_payment_method_data: None,
},
+ PaymentMethodUpdate::NetworkTokenDataUpdate {
+ network_token_requestor_reference_id,
+ network_token_locker_id,
+ network_token_payment_method_data,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ status: None,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ updated_by: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
+ last_modified: common_utils::date_time::now(),
+ network_transaction_id: None,
+ network_token_requestor_reference_id,
+ network_token_locker_id,
+ network_token_payment_method_data,
+ },
}
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 49a75735ea4..4073b7a4d9b 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -57,9 +57,12 @@ use masking::Secret;
use router_env::{instrument, metrics::add_attributes, tracing};
use strum::IntoEnumIterator;
-use super::surcharge_decision_configs::{
- perform_surcharge_decision_management_for_payment_method_list,
- perform_surcharge_decision_management_for_saved_cards,
+use super::{
+ migration::RecordMigrationStatusBuilder,
+ surcharge_decision_configs::{
+ perform_surcharge_decision_management_for_payment_method_list,
+ perform_surcharge_decision_management_for_saved_cards,
+ },
};
#[cfg(all(
any(feature = "v2", feature = "v1"),
@@ -376,7 +379,7 @@ pub async fn migrate_payment_method(
merchant_id: &id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
+) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {
let mut req = req;
let card_details = req.card.as_ref().get_required_value("card")?;
@@ -405,34 +408,92 @@ pub async fn migrate_payment_method(
.await?;
};
- match card_number_validation_result {
+ let should_require_connector_mandate_details = req.network_token.is_none();
+
+ let mut migration_status = RecordMigrationStatusBuilder::new();
+
+ let resp = match card_number_validation_result {
Ok(card_number) => {
let payment_method_create_request =
api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
card_number,
&req,
);
+
+ logger::debug!("Storing the card in locker and migrating the payment method");
get_client_secret_or_add_payment_method_for_migration(
&state,
payment_method_create_request,
merchant_account,
key_store,
+ &mut migration_status,
)
- .await
+ .await?
}
Err(card_validation_error) => {
logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}");
skip_locker_call_and_migrate_payment_method(
- state,
+ &state,
&req,
merchant_id.to_owned(),
key_store,
merchant_account,
card_bin_details.clone(),
+ should_require_connector_mandate_details,
+ &mut migration_status,
)
- .await
+ .await?
}
- }
+ };
+ let payment_method_response = match resp {
+ services::ApplicationResponse::Json(response) => response,
+ _ => Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch the payment method response")?,
+ };
+
+ let pm_id = payment_method_response.payment_method_id.clone();
+
+ let network_token = req.network_token.clone();
+
+ let network_token_migrated = match network_token {
+ Some(nt_detail) => {
+ logger::debug!("Network token migration");
+ let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone();
+ let network_token_data = &nt_detail.network_token_data;
+
+ Some(
+ save_network_token_and_update_payment_method(
+ &state,
+ &req,
+ key_store,
+ merchant_account,
+ network_token_data,
+ network_token_requestor_ref_id,
+ pm_id,
+ )
+ .await
+ .map_err(|err| logger::error!(?err, "Failed to save network token"))
+ .ok()
+ .unwrap_or_default(),
+ )
+ }
+ None => {
+ logger::debug!("Network token data is not available");
+ None
+ }
+ };
+ migration_status.network_token_migrated(network_token_migrated);
+ let migrate_status = migration_status.build();
+
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentMethodMigrateResponse {
+ payment_method_response,
+ card_migrated: migrate_status.card_migrated,
+ network_token_migrated: migrate_status.network_token_migrated,
+ connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,
+ network_transaction_id_migrated: migrate_status.network_transaction_migrated,
+ },
+ ))
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
@@ -442,7 +503,7 @@ pub async fn migrate_payment_method(
_merchant_id: &id_type::MerchantId,
_merchant_account: &domain::MerchantAccount,
_key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
+) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {
todo!()
}
@@ -645,31 +706,49 @@ impl
not(feature = "payment_methods_v2"),
not(feature = "customer_v2")
))]
+#[allow(clippy::too_many_arguments)]
pub async fn skip_locker_call_and_migrate_payment_method(
- state: routes::SessionState,
+ state: &routes::SessionState,
req: &api::PaymentMethodMigrate,
merchant_id: id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
card: api_models::payment_methods::CardDetailFromLocker,
+ should_require_connector_mandate_details: bool,
+ migration_status: &mut RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
// In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details.
- let connector_mandate_details_req = req
- .connector_mandate_details
- .clone()
- .get_required_value("connector mandate details")?;
+ //if network token data is present, then connector mandate details are not mandatory
- let connector_mandate_details = serde_json::to_value(&connector_mandate_details_req)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to parse connector mandate details")?;
- let key_manager_state = (&state).into();
+ let connector_mandate_details = if should_require_connector_mandate_details {
+ let connector_mandate_details_req = req
+ .connector_mandate_details
+ .clone()
+ .get_required_value("connector mandate details")?;
+
+ Some(
+ serde_json::to_value(&connector_mandate_details_req)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse connector mandate details")?,
+ )
+ } else {
+ req.connector_mandate_details
+ .clone()
+ .map(|connector_mandate_details_req| {
+ serde_json::to_value(&connector_mandate_details_req)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse connector mandate details")
+ })
+ .transpose()?
+ };
+ let key_manager_state = &state.into();
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
- .async_map(|billing| create_encrypted_data(&key_manager_state, key_store, billing))
+ .async_map(|billing| create_encrypted_data(key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -677,7 +756,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
let customer = db
.find_customer_by_customer_id_merchant_id(
- &(&state).into(),
+ &state.into(),
&customer_id,
&merchant_id,
key_store,
@@ -690,7 +769,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()));
let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(
- create_encrypted_data(&key_manager_state, key_store, payment_method_card_details)
+ create_encrypted_data(key_manager_state, key_store, payment_method_card_details)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method card details")?,
@@ -699,13 +778,26 @@ pub async fn skip_locker_call_and_migrate_payment_method(
let payment_method_metadata: Option<serde_json::Value> =
req.metadata.as_ref().map(|data| data.peek()).cloned();
+ let network_transaction_id = req.network_transaction_id.clone();
+
+ migration_status.network_transaction_id_migrated(network_transaction_id.as_ref().map(|_| true));
+
+ migration_status.connector_mandate_details_migrated(
+ connector_mandate_details
+ .as_ref()
+ .map(|_| true)
+ .or_else(|| req.connector_mandate_details.as_ref().map(|_| false)),
+ );
+
+ migration_status.card_migrated(false);
+
let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
- &(&state).into(),
+ &state.into(),
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
@@ -718,11 +810,11 @@ pub async fn skip_locker_call_and_migrate_payment_method(
scheme: req.card_network.clone().or(card.scheme.clone()),
metadata: payment_method_metadata.map(Secret::new),
payment_method_data: payment_method_data_encrypted.map(Into::into),
- connector_mandate_details: Some(connector_mandate_details),
+ connector_mandate_details,
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::Active,
- network_transaction_id: None,
+ network_transaction_id,
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
@@ -753,7 +845,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
- &state,
+ state,
&merchant_id,
key_store.clone(),
&customer_id,
@@ -768,6 +860,117 @@ pub async fn skip_locker_call_and_migrate_payment_method(
))
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
+#[allow(clippy::too_many_arguments)]
+pub async fn save_network_token_and_update_payment_method(
+ state: &routes::SessionState,
+ req: &api::PaymentMethodMigrate,
+ key_store: &domain::MerchantKeyStore,
+ merchant_account: &domain::MerchantAccount,
+ network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,
+ network_token_requestor_ref_id: String,
+ pm_id: String,
+) -> errors::RouterResult<bool> {
+ let payment_method_create_request =
+ api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(
+ network_token_data.network_token_number.clone(),
+ req,
+ );
+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
+
+ let network_token_details = api::CardDetail {
+ card_number: network_token_data.network_token_number.clone(),
+ card_exp_month: network_token_data.network_token_exp_month.clone(),
+ card_exp_year: network_token_data.network_token_exp_year.clone(),
+ card_holder_name: network_token_data.card_holder_name.clone(),
+ nick_name: network_token_data.nick_name.clone(),
+ card_issuing_country: network_token_data.card_issuing_country.clone(),
+ card_network: network_token_data.card_network.clone(),
+ card_issuer: network_token_data.card_issuer.clone(),
+ card_type: network_token_data.card_type.clone(),
+ };
+
+ logger::debug!(
+ "Adding network token to locker for customer_id: {:?}",
+ customer_id
+ );
+
+ let token_resp = Box::pin(add_card_to_locker(
+ state,
+ payment_method_create_request.clone(),
+ &network_token_details,
+ &customer_id,
+ merchant_account,
+ None,
+ ))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Add Network Token failed");
+ let key_manager_state = &state.into();
+
+ match token_resp {
+ Ok(resp) => {
+ logger::debug!("Network token added to locker");
+ let (token_pm_resp, _duplication_check) = resp;
+ let pm_token_details = token_pm_resp
+ .card
+ .as_ref()
+ .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));
+ let pm_network_token_data_encrypted = pm_token_details
+ .async_map(|pm_card| create_encrypted_data(key_manager_state, key_store, pm_card))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt payment method data")?;
+
+ let pm_update = storage::PaymentMethodUpdate::NetworkTokenDataUpdate {
+ network_token_requestor_reference_id: Some(network_token_requestor_ref_id),
+ network_token_locker_id: Some(token_pm_resp.payment_method_id),
+ network_token_payment_method_data: pm_network_token_data_encrypted.map(Into::into),
+ };
+ let db = &*state.store;
+ let existing_pm = db
+ .find_payment_method(
+ &state.into(),
+ key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to fetch payment method for existing pm_id: {:?} in db",
+ pm_id
+ ))?;
+
+ db.update_payment_method(
+ &state.into(),
+ key_store,
+ existing_pm,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to update payment method for existing pm_id: {:?} in db",
+ pm_id
+ ))?;
+
+ logger::debug!("Network token added to locker and payment method updated");
+ Ok(true)
+ }
+ Err(err) => {
+ logger::debug!("Network token added to locker failed {:?}", err);
+ Ok(false)
+ }
+ }
+}
+
// need to discuss regarding the migration APIs for v2
#[cfg(all(
feature = "v2",
@@ -899,6 +1102,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
+ migration_status: &mut RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
@@ -908,6 +1112,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
#[cfg(feature = "payouts")]
let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
let key_manager_state = state.into();
+
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
.billing
.clone()
@@ -930,6 +1135,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
req,
merchant_account,
key_store,
+ migration_status,
))
.await
} else {
@@ -946,7 +1152,7 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
None,
None,
key_store,
- connector_mandate_details,
+ connector_mandate_details.clone(),
Some(enums::PaymentMethodStatus::AwaitingData),
None,
merchant_account.storage_scheme,
@@ -957,6 +1163,14 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
None,
)
.await?;
+ migration_status.connector_mandate_details_migrated(
+ connector_mandate_details
+ .clone()
+ .map(|_| true)
+ .or_else(|| req.connector_mandate_details.clone().map(|_| false)),
+ );
+
+ migration_status.card_migrated(false);
if res.status == enums::PaymentMethodStatus::AwaitingData {
add_payment_method_status_update_task(
@@ -1482,6 +1696,7 @@ pub async fn save_migration_payment_method(
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
+ migration_status: &mut RecordMigrationStatusBuilder,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
@@ -1505,6 +1720,17 @@ pub async fn save_migration_payment_method(
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let network_transaction_id = req.network_transaction_id.clone();
+
+ migration_status.network_transaction_id_migrated(network_transaction_id.as_ref().map(|_| true));
+
+ migration_status.connector_mandate_details_migrated(
+ connector_mandate_details
+ .as_ref()
+ .map(|_| true)
+ .or_else(|| req.connector_mandate_details.as_ref().map(|_| false)),
+ );
+
let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
@@ -1564,6 +1790,7 @@ pub async fn save_migration_payment_method(
let (mut resp, duplication_check) = response?;
+ migration_status.card_migrated(true);
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
@@ -1714,7 +1941,7 @@ pub async fn save_migration_payment_method(
None,
locker_id,
connector_mandate_details,
- req.network_transaction_id.clone(),
+ network_transaction_id,
merchant_account.storage_scheme,
payment_method_billing_address.map(Into::into),
None,
diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs
index b0aaa767a4e..11bc3a9d74f 100644
--- a/crates/router/src/core/payment_methods/migration.rs
+++ b/crates/router/src/core/payment_methods/migration.rs
@@ -149,3 +149,64 @@ fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> {
})
}
}
+
+#[derive(Debug)]
+pub struct RecordMigrationStatus {
+ pub card_migrated: Option<bool>,
+ pub network_token_migrated: Option<bool>,
+ pub connector_mandate_details_migrated: Option<bool>,
+ pub network_transaction_migrated: Option<bool>,
+}
+
+#[derive(Debug)]
+pub struct RecordMigrationStatusBuilder {
+ pub card_migrated: Option<bool>,
+ pub network_token_migrated: Option<bool>,
+ pub connector_mandate_details_migrated: Option<bool>,
+ pub network_transaction_migrated: Option<bool>,
+}
+
+impl RecordMigrationStatusBuilder {
+ pub fn new() -> Self {
+ Self {
+ card_migrated: None,
+ network_token_migrated: None,
+ connector_mandate_details_migrated: None,
+ network_transaction_migrated: None,
+ }
+ }
+
+ pub fn card_migrated(&mut self, card_migrated: bool) {
+ self.card_migrated = Some(card_migrated);
+ }
+
+ pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) {
+ self.network_token_migrated = network_token_migrated;
+ }
+
+ pub fn connector_mandate_details_migrated(
+ &mut self,
+ connector_mandate_details_migrated: Option<bool>,
+ ) {
+ self.connector_mandate_details_migrated = connector_mandate_details_migrated;
+ }
+
+ pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) {
+ self.network_transaction_migrated = network_transaction_migrated;
+ }
+
+ pub fn build(self) -> RecordMigrationStatus {
+ RecordMigrationStatus {
+ card_migrated: self.card_migrated,
+ network_token_migrated: self.network_token_migrated,
+ connector_mandate_details_migrated: self.connector_mandate_details_migrated,
+ network_transaction_migrated: self.network_transaction_migrated,
+ }
+ }
+}
+
+impl Default for RecordMigrationStatusBuilder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 4bae04e1426..a6f3018ed0d 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -973,7 +973,7 @@ pub async fn save_network_token_in_locker(
{
Ok((token_response, network_token_requestor_ref_id)) => {
// Only proceed if the tokenization was successful
- let card_data = api::CardDetail {
+ let network_token_data = api::CardDetail {
card_number: token_response.token.clone(),
card_exp_month: token_response.token_expiry_month.clone(),
card_exp_year: token_response.token_expiry_year.clone(),
@@ -988,7 +988,7 @@ pub async fn save_network_token_in_locker(
let (res, dc) = Box::pin(payment_methods::cards::add_card_to_locker(
state,
payment_method_request,
- &card_data,
+ &network_token_data,
&customer_id,
merchant_account,
None,
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 8b1175d5cc6..25227ae5383 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -7,9 +7,10 @@ pub use api_models::payment_methods::{
PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
PaymentMethodIntentConfirm, PaymentMethodIntentConfirmInternal, PaymentMethodIntentCreate,
PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
- PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate,
- PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
- TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse,
+ PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData,
+ TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
+ TokenizedWalletValue1, TokenizedWalletValue2,
};
#[cfg(all(
any(feature = "v2", feature = "v1"),
@@ -22,9 +23,9 @@ pub use api_models::payment_methods::{
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate,
- PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted,
- TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1,
- TokenizedWalletValue2,
+ PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
+ TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
+ TokenizedWalletValue1, TokenizedWalletValue2,
};
use error_stack::report;
| 2024-10-13T21:59:05Z |
## Description
<!-- Describe your changes in detail -->
Add support for network token migration.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
test migration api.
req -
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api-key' \
--data '{
"merchant_id": "merchant_id",
"card": {
"card_number": "card_number",
"card_exp_month": "12",
"card_exp_year": "21",
"card_holder_name": "joseph Doe"
},
"customer_id": "customer_id",
"network_transaction_id": "nt-transaction-id",
"payment_method": "card",
"network_token": {
"network_token_data": {
"network_token_number": "network_token_number",
"network_token_exp_month": "12",
"network_token_exp_year": "21"
},
"network_token_requestor_ref_id": "test-ref-id"
}
}'
```
expected response -
```
{
"payment_method_response": {
"merchant_id": "merchant_1731400520",
"customer_id": "cust-1731400905",
"payment_method_id": "pm_LSk7YuLskFS8aBdWNvzk",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "0000",
"expiry_month": "12",
"expiry_year": "21",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "420000",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"metadata": null,
"created": "2024-11-12T09:00:50.948Z",
"last_used_at": "2024-11-12T09:00:50.949Z",
"client_secret": "pm_LSk7YuLskFS8aBdWNvzk_secret_6B5AfKanyCDhy5hjeUce"
},
"card_migrated": true,
"network_token_migrated": true,
"connector_mandate_details_migrated": null,
"network_transaction_id_migrated": true
}
```
<img width="1148" alt="Screenshot 2024-11-12 at 2 31 12 PM" src="https://github.com/user-attachments/assets/e3661f77-075e-4768-bac1-c2b23e0c12ce"> | 43d87913ab3d177a6d193b3e475c96609cc09a28 |
test migration api.
req -
```
curl --location 'http://localhost:8080/payment_methods/migrate' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api-key' \
--data '{
"merchant_id": "merchant_id",
"card": {
"card_number": "card_number",
"card_exp_month": "12",
"card_exp_year": "21",
"card_holder_name": "joseph Doe"
},
"customer_id": "customer_id",
"network_transaction_id": "nt-transaction-id",
"payment_method": "card",
"network_token": {
"network_token_data": {
"network_token_number": "network_token_number",
"network_token_exp_month": "12",
"network_token_exp_year": "21"
},
"network_token_requestor_ref_id": "test-ref-id"
}
}'
```
expected response -
```
{
"payment_method_response": {
"merchant_id": "merchant_1731400520",
"customer_id": "cust-1731400905",
"payment_method_id": "pm_LSk7YuLskFS8aBdWNvzk",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "0000",
"expiry_month": "12",
"expiry_year": "21",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "420000",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"metadata": null,
"created": "2024-11-12T09:00:50.948Z",
"last_used_at": "2024-11-12T09:00:50.949Z",
"client_secret": "pm_LSk7YuLskFS8aBdWNvzk_secret_6B5AfKanyCDhy5hjeUce"
},
"card_migrated": true,
"network_token_migrated": true,
"connector_mandate_details_migrated": null,
"network_transaction_id_migrated": true
}
```
<img width="1148" alt="Screenshot 2024-11-12 at 2 31 12 PM" src="https://github.com/user-attachments/assets/e3661f77-075e-4768-bac1-c2b23e0c12ce">
| [
"crates/api_models/src/events/payment.rs",
"crates/api_models/src/payment_methods.rs",
"crates/diesel_models/src/payment_method.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payment_methods/migration.rs",
"crates/router/src/core/payments/tokenization.rs",
"crates/router... | |
juspay/hyperswitch | juspay__hyperswitch-6024 | Bug: [REFACTOR]: [WELLSFARGO] Add amount conversion framework to Wellsfargo
### :memo: Feature Description
Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows.
Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application.
### :hammer: Possible Implementation
- For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly.
- Connectors should invoke the `convert` function to receive the amount in their required format.
- Refer to the [connector documentation](https://developer.wellsfargo.com/guides/user-guides/open-banking-europe-api-integration/obei#step-1-%E2%80%93-request-payment-initiation) to determine the required amount format for each connector.
- You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context.
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [ ] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
| diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 0cad88bfd4f..1c0ca722f29 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -580,6 +580,10 @@ impl StringMajorUnit {
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
+ /// forms a new StringMajorUnit default unit i.e zero
+ pub fn zero() -> Self {
+ Self("0".to_string())
+ }
/// Get string amount from struct to be removed in future
pub fn get_amount_as_string(&self) -> String {
diff --git a/crates/router/src/connector/wellsfargo.rs b/crates/router/src/connector/wellsfargo.rs
index f5cdb6431b3..a63007f0a27 100644
--- a/crates/router/src/connector/wellsfargo.rs
+++ b/crates/router/src/connector/wellsfargo.rs
@@ -1,9 +1,10 @@
pub mod transformers;
-use std::fmt::Debug;
-
use base64::Engine;
-use common_utils::request::RequestContent;
+use common_utils::{
+ request::RequestContent,
+ types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
+};
use diesel_models::enums;
use error_stack::{report, Report, ResultExt};
use masking::{ExposeInterface, PeekInterface};
@@ -12,6 +13,7 @@ use time::OffsetDateTime;
use transformers as wellsfargo;
use url::Url;
+use super::utils::convert_amount;
use crate::{
configs::settings,
connector::{
@@ -35,10 +37,18 @@ use crate::{
utils::BytesExt,
};
-#[derive(Debug, Clone)]
-pub struct Wellsfargo;
+#[derive(Clone)]
+pub struct Wellsfargo {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
+}
impl Wellsfargo {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMajorUnitForConnector,
+ }
+ }
+
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
@@ -600,12 +610,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = wellsfargo::WellsfargoRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ MinorUnit::new(req.request.amount_to_capture),
req.request.currency,
- req.request.amount_to_capture,
- req,
- ))?;
+ )?;
+
+ let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
+
let connector_req =
wellsfargo::WellsfargoPaymentsCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -792,12 +804,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = wellsfargo::WellsfargoRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ MinorUnit::new(req.request.amount),
req.request.currency,
- req.request.amount,
- req,
- ))?;
+ )?;
+
+ let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req =
wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -915,20 +928,21 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = wellsfargo::WellsfargoRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ MinorUnit::new(req.request.amount.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "Amount",
+ },
+ )?),
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?,
- req.request
- .amount
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "Amount",
- })?,
- req,
- ))?;
+ )?;
+
+ let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req = wellsfargo::WellsfargoVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -1040,12 +1054,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundExecuteRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = wellsfargo::WellsfargoRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ MinorUnit::new(req.request.refund_amount),
req.request.currency,
- req.request.refund_amount,
- req,
- ))?;
+ )?;
+
+ let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -1204,12 +1219,13 @@ impl
req: &types::PaymentsIncrementalAuthorizationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = wellsfargo::WellsfargoRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ MinorUnit::new(req.request.additional_amount),
req.request.currency,
- req.request.additional_amount,
- req,
- ))?;
+ )?;
+
+ let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_request =
wellsfargo::WellsfargoPaymentsIncrementalAuthorizationRequest::try_from(
&connector_router_data,
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index ee34c26d670..b5adaf9545b 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -1,7 +1,10 @@
use api_models::payments;
use base64::Engine;
use common_enums::FutureUsage;
-use common_utils::{pii, types::SemanticVersion};
+use common_utils::{
+ pii,
+ types::{SemanticVersion, StringMajorUnit},
+};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -26,21 +29,16 @@ use crate::{
#[derive(Debug, Serialize)]
pub struct WellsfargoRouterData<T> {
- pub amount: String,
+ pub amount: StringMajorUnit,
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WellsfargoRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
- ) -> Result<Self, Self::Error> {
- // This conversion function is used at different places in the file, if updating this, keep a check for those
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
- Ok(Self {
+impl<T> From<(StringMajorUnit, T)> for WellsfargoRouterData<T> {
+ fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
+ Self {
amount,
- router_data: item,
- })
+ router_data,
+ }
}
}
@@ -61,7 +59,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
let order_information = OrderInformationWithBill {
amount_details: Amount {
- total_amount: "0".to_string(),
+ total_amount: StringMajorUnit::zero(),
currency: item.request.currency,
},
bill_to: Some(bill_to),
@@ -471,14 +469,14 @@ pub struct OrderInformation {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Amount {
- total_amount: String,
+ total_amount: StringMajorUnit,
currency: api_models::enums::Currency,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalAmount {
- additional_amount: String,
+ additional_amount: StringMajorUnit,
currency: String,
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index e115558995d..851cda7143c 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -510,7 +510,7 @@ impl ConnectorData {
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Wellsfargo)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new())))
}
// enums::Connector::Wellsfargopayout => {
diff --git a/crates/router/tests/connectors/wellsfargo.rs b/crates/router/tests/connectors/wellsfargo.rs
index 4425c077377..cab82c59ac8 100644
--- a/crates/router/tests/connectors/wellsfargo.rs
+++ b/crates/router/tests/connectors/wellsfargo.rs
@@ -11,7 +11,7 @@ impl utils::Connector for WellsfargoTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Wellsfargo;
utils::construct_connector_data_old(
- Box::new(&Wellsfargo),
+ Box::new(Wellsfargo::new()),
types::Connector::Wellsfargo,
api::GetToken::Connector,
None,
| 2024-10-13T18:46:13Z |
## Description
<!-- Describe your changes in detail -->
This PR do amount conversion changes for Wellsfargo Connector and it accepts the amount in StringMajorUnit
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6024 | 19a8474d8731ed7149b541f02ad237e30c4c9f24 | [
"crates/common_utils/src/types.rs",
"crates/router/src/connector/wellsfargo.rs",
"crates/router/src/connector/wellsfargo/transformers.rs",
"crates/router/src/types/api.rs",
"crates/router/tests/connectors/wellsfargo.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6294 | Bug: [BUG] Broken link to FAQs
### Bug Description
The link in this line:
https://github.com/juspay/hyperswitch/blob/19a8474d8731ed7149b541f02ad237e30c4c9f24/README.md?plain=1#L317
is broken.
### Expected Behavior
When I click the link I should be taken to some FAQ page.
### Actual Behavior
When I click that link I am taken to: https://docs.hyperswitch.io/
### Steps To Reproduce
1. Go to the [FAQ section](https://github.com/juspay/hyperswitch?tab=readme-ov-file#FAQs),
2. Click the link.
### Context For The Bug
Since https://hyperswitch.io/docs/devSupport does not exist anymore and each feature has its own FAQ, I would suggest to remove the entire FAQ section in the main README.md file.
### Environment
Not relevant.
### 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/README.md b/README.md
index f5c27411b51..3814ac925ad 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,6 @@ The single API to access payment ecosystems across 130+ countries</div>
<a href="#community">Community</a> •
<a href="#bugs-and-feature-requests">Bugs and feature requests</a> •
<a href="#versioning">Versioning</a> •
- <a href="#FAQs">FAQs</a> •
<a href="#copyright-and-license">Copyright and License</a>
</p>
@@ -309,15 +308,6 @@ If your problem or idea is not addressed yet, please [open a new issue].
Check the [CHANGELOG.md](./CHANGELOG.md) file for details.
-<a href="#FAQs">
- <h2 id="FAQs">🤔 FAQs</h2>
-</a>
-
-Got more questions?
-Please refer to our [FAQs page][faqs].
-
-[faqs]: https://hyperswitch.io/docs/devSupport
-
<a href="#©Copyright and License">
<h2 id="copyright-and-license">©️ Copyright and License</h2>
</a>
| 2024-10-13T15:06:32Z |
## 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 #6294.
## How did you test 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 check of the README.md file. | 2a53f52f994ca98a31509f05e31b3874b88d15bf |
Manual check of the README.md file.
| [
"README.md"
] | |
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 |
## 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)?
--> | 9597215a66e38b0021bd804ffe4d9d040e30f8f9 | [
"crates/router/src/connector/rapyd/transformers.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6111 | Bug: [FEATURE] Extend the BatchSampleDataInterface Trait for Disputes
### Feature Description
The issue is sub part of issue: #5991
We currently have a feature for generating sample data, which includes batch insertion of payments and refunds. The feature inserts payments and refunds in batches using the BatchSampleDataInterface trait. We need to extend this functionality to support batch insertion and deletion of disputes as well.
Steps to Implement Batch Support for Disputes
**Extend the BatchSampleDataInterface Trait**
We need to extend the existing BatchSampleDataInterface to include methods for batch insertion and deletion of disputes. These methods will be similar to the ones already implemented for PaymentIntent, PaymentAttempt, and Refund.
**New Methods for Disputes:**
`insert_disputes_batch_for_sample_data`: This method will handle batch insertion of disputes.
`delete_disputes_for_sample_data`: This method will handle (batch) deletion of disputes.
### Possible Implementation
Add Functions for Dispute Insert and Delete in `BatchSampleDataInterface`
- File: `crates/router/src/db/user/sample_data.rs`
- Extend the existing BatchSampleDataInterface to include the methods for inserting and deleting disputes.
Complete these interface functions for Store, Mock Db and Kafka like we did for other functions.
Write Batch Insert and Delete Queries for Disputes
- File: `crates/diesel_model/src/query/user/sample_data.rs`
- Define the queries (using diesel) to handle batch insertion and deletion of disputes, similar to how they are handled for payments and refunds.
To test we can hard code some dummy dispute and try inserting using the function we made in core. We can check Db and see the logs for the query that is getting printed.
Steps for Testing Dispute Batch Insertion and Deletion
- To verify the batch insertion and deletion of disputes using the functions implemented in the BatchSampleDataInterface, we can perform a simple test by hardcoding some dummy dispute data.
- Once we have the dummy dispute data, we can use the `generate_sample_data_for_user` method from the core function to insert the disputes into the database. This should invoke the appropriate batch insertion logic. (Or we can make an api to test the behaviour when the function is invoked)
Curl to invoke this core function:
```
curl --location 'http://localhost:8080/user/sample_data' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
The JWT token we can get from signup and then skipping the 2FA:
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "JohnTest@test.com",
"password": "Test@321"
}'
```
This will give an intermediate token in response, we need to use this token to skip 2FA
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: Bearer Intermediatetoken'
```
This will give us JWT Token that we can use to hit the sample_data api
Curl to delete sample data (The core function for sample dispute delete can be used to our advantage):
```
curl --location --request DELETE 'http://localhost:8080/user/sample_data' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
- We can check Database Logs and Printed Queries whether the appropriate queries are getting printed
- We can also manually check DB
Note: Omit the Code for Testing part in the PR raised, have only Insert and Delete logic related to the DB, include the relevant logs and screenshots after test.
The Sample disputes generation part, we will be handling in the separate PR. (#6117 )
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None | diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs
index b5400f570a3..27e674f7d7b 100644
--- a/crates/diesel_models/src/query/user/sample_data.rs
+++ b/crates/diesel_models/src/query/user/sample_data.rs
@@ -12,9 +12,11 @@ use crate::schema_v2::{
payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl,
};
use crate::{
- errors, schema::refund::dsl as refund_dsl, user::sample_data::PaymentAttemptBatchNew,
- PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew,
- StorageResult,
+ errors,
+ schema::{dispute::dsl as dispute_dsl, refund::dsl as refund_dsl},
+ user::sample_data::PaymentAttemptBatchNew,
+ Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund,
+ RefundNew, StorageResult,
};
pub async fn insert_payment_intents(
@@ -61,6 +63,21 @@ pub async fn insert_refunds(
.attach_printable("Error while inserting refunds")
}
+pub async fn insert_disputes(
+ conn: &PgPooledConn,
+ batch: Vec<DisputeNew>,
+) -> StorageResult<Vec<Dispute>> {
+ let query = diesel::insert_into(<Dispute>::table()).values(batch);
+
+ logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ query
+ .get_results_async(conn)
+ .await
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Error while inserting disputes")
+}
+
#[cfg(feature = "v1")]
pub async fn delete_payment_intents(
conn: &PgPooledConn,
@@ -165,3 +182,29 @@ pub async fn delete_refunds(
_ => Ok(result),
})
}
+
+pub async fn delete_disputes(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+) -> StorageResult<Vec<Dispute>> {
+ let query = diesel::delete(<Dispute>::table())
+ .filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned()))
+ .filter(dispute_dsl::dispute_id.like("test_%"));
+
+ logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ query
+ .get_results_async(conn)
+ .await
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Error while deleting disputes")
+ .and_then(|result| match result.len() {
+ n if n > 0 => {
+ logger::debug!("{n} records deleted");
+ Ok(result)
+ }
+ 0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
+ .attach_printable("No records deleted")),
+ _ => Ok(result),
+ })
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9f237c226b6..6e9daeedc59 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3239,6 +3239,26 @@ impl BatchSampleDataInterface for KafkaStore {
Ok(refunds_list)
}
+ #[cfg(feature = "v1")]
+ async fn insert_disputes_batch_for_sample_data(
+ &self,
+ batch: Vec<diesel_models::DisputeNew>,
+ ) -> CustomResult<Vec<diesel_models::Dispute>, hyperswitch_domain_models::errors::StorageError>
+ {
+ let disputes_list = self
+ .diesel_store
+ .insert_disputes_batch_for_sample_data(batch)
+ .await?;
+
+ for dispute in disputes_list.iter() {
+ let _ = self
+ .kafka_producer
+ .log_dispute(dispute, None, self.tenant_id.clone())
+ .await;
+ }
+ Ok(disputes_list)
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
@@ -3306,6 +3326,27 @@ impl BatchSampleDataInterface for KafkaStore {
Ok(refunds_list)
}
+
+ #[cfg(feature = "v1")]
+ async fn delete_disputes_for_sample_data(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ ) -> CustomResult<Vec<diesel_models::Dispute>, hyperswitch_domain_models::errors::StorageError>
+ {
+ let disputes_list = self
+ .diesel_store
+ .delete_disputes_for_sample_data(merchant_id)
+ .await?;
+
+ for dispute in disputes_list.iter() {
+ let _ = self
+ .kafka_producer
+ .log_dispute_delete(dispute, self.tenant_id.clone())
+ .await;
+ }
+
+ Ok(disputes_list)
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs
index 709ff4a358a..3add7b744d0 100644
--- a/crates/router/src/db/user/sample_data.rs
+++ b/crates/router/src/db/user/sample_data.rs
@@ -1,5 +1,6 @@
use common_utils::types::keymanager::KeyManagerState;
use diesel_models::{
+ dispute::{Dispute, DisputeNew},
errors::DatabaseError,
query::user::sample_data as sample_data_queries,
refund::{Refund, RefundNew},
@@ -39,6 +40,12 @@ pub trait BatchSampleDataInterface {
batch: Vec<RefundNew>,
) -> CustomResult<Vec<Refund>, StorageError>;
+ #[cfg(feature = "v1")]
+ async fn insert_disputes_batch_for_sample_data(
+ &self,
+ batch: Vec<DisputeNew>,
+ ) -> CustomResult<Vec<Dispute>, StorageError>;
+
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
@@ -58,6 +65,12 @@ pub trait BatchSampleDataInterface {
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError>;
+
+ #[cfg(feature = "v1")]
+ async fn delete_disputes_for_sample_data(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<Dispute>, StorageError>;
}
#[async_trait::async_trait]
@@ -127,6 +140,19 @@ impl BatchSampleDataInterface for Store {
.map_err(diesel_error_to_data_error)
}
+ #[cfg(feature = "v1")]
+ async fn insert_disputes_batch_for_sample_data(
+ &self,
+ batch: Vec<DisputeNew>,
+ ) -> CustomResult<Vec<Dispute>, StorageError> {
+ let conn = pg_connection_write(self)
+ .await
+ .change_context(StorageError::DatabaseConnectionError)?;
+ sample_data_queries::insert_disputes(&conn, batch)
+ .await
+ .map_err(diesel_error_to_data_error)
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
@@ -184,6 +210,19 @@ impl BatchSampleDataInterface for Store {
.await
.map_err(diesel_error_to_data_error)
}
+
+ #[cfg(feature = "v1")]
+ async fn delete_disputes_for_sample_data(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<Dispute>, StorageError> {
+ let conn = pg_connection_write(self)
+ .await
+ .change_context(StorageError::DatabaseConnectionError)?;
+ sample_data_queries::delete_disputes(&conn, merchant_id)
+ .await
+ .map_err(diesel_error_to_data_error)
+ }
}
#[async_trait::async_trait]
@@ -214,6 +253,14 @@ impl BatchSampleDataInterface for storage_impl::MockDb {
Err(StorageError::MockDbError)?
}
+ #[cfg(feature = "v1")]
+ async fn insert_disputes_batch_for_sample_data(
+ &self,
+ _batch: Vec<DisputeNew>,
+ ) -> CustomResult<Vec<Dispute>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
+
#[cfg(feature = "v1")]
async fn delete_payment_intents_for_sample_data(
&self,
@@ -239,6 +286,14 @@ impl BatchSampleDataInterface for storage_impl::MockDb {
) -> CustomResult<Vec<Refund>, StorageError> {
Err(StorageError::MockDbError)?
}
+
+ #[cfg(feature = "v1")]
+ async fn delete_disputes_for_sample_data(
+ &self,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Vec<Dispute>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
}
// TODO: This error conversion is re-used from storage_impl and is not DRY when it should be
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 4fd692e1166..51ae9456ecc 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -582,6 +582,21 @@ impl KafkaProducer {
.attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}"))
}
+ pub async fn log_dispute_delete(
+ &self,
+ delete_old_dispute: &Dispute,
+ tenant_id: TenantID,
+ ) -> MQResult<()> {
+ self.log_event(&KafkaEvent::old(
+ &KafkaDispute::from_storage(delete_old_dispute),
+ tenant_id.clone(),
+ self.ckh_database_name.clone(),
+ ))
+ .attach_printable_lazy(|| {
+ format!("Failed to add negative dispute event {delete_old_dispute:?}")
+ })
+ }
+
#[cfg(feature = "payouts")]
pub async fn log_payout(
&self,
| 2024-10-11T13:39:20Z |
## Description
<!-- Describe your changes in detail -->
I've extended the interface for `BatchSampleDataInterface` to with `insert_disputes_batch_for_sample_data` and `delete_disputes_for_sample_data`, and added implementation to all structs implementing this trait. I've also modified `generate_sample_data` function in `utils/user/sample_data.rs` to generate dispute data, and `delete_sample_data_for_user` function in `core/user/sample_data.rs` to delete the generated dispute data.
The overall result is the `/user/sample_data` endpoint now supports dispute data generation and deletion.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
resolve #6111
## How did you test 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 test is done, screenshots are provided in the comment section of this issue: https://github.com/juspay/hyperswitch/issues/6111 | 53e82c3faef3ee629a38180e3882a2920332a9a8 |
Manual test is done, screenshots are provided in the comment section of this issue: https://github.com/juspay/hyperswitch/issues/6111
| [
"crates/diesel_models/src/query/user/sample_data.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user/sample_data.rs",
"crates/router/src/services/kafka.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6290 | Bug: [DOCS]: Add `X-Merchant-Id` to headers in Profile endpoints for v2
### Description
We require `X-Merchant-Id` in the headers for the following endpoints in Profile:
- Profile - Create
- Profile - Update
- Profile - Retrieve
- Merchant Connector - List
We need to update the v2 API documentation. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 3f57faaf1d7..46c4868e4bd 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -711,6 +711,20 @@
"summary": "Profile - Create",
"description": "Creates a new *profile* for a merchant",
"operationId": "Create A Profile",
+ "parameters": [
+ {
+ "name": "X-Merchant-Id",
+ "in": "header",
+ "description": "Merchant ID of the profile.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -767,6 +781,18 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "X-Merchant-Id",
+ "in": "header",
+ "description": "Merchant ID of the profile.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"
+ }
}
],
"responses": {
@@ -806,6 +832,18 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "X-Merchant-Id",
+ "in": "header",
+ "description": "Merchant ID of the profile.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"
+ }
}
],
"requestBody": {
@@ -864,6 +902,18 @@
"schema": {
"type": "string"
}
+ },
+ {
+ "name": "X-Merchant-Id",
+ "in": "header",
+ "description": "Merchant ID of the profile.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"
+ }
}
],
"responses": {
diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs
index f726c76db84..fc56e642719 100644
--- a/crates/openapi/src/routes/profile.rs
+++ b/crates/openapi/src/routes/profile.rs
@@ -139,6 +139,13 @@ pub async fn profile_list() {}
#[utoipa::path(
post,
path = "/v2/profiles",
+ params(
+ (
+ "X-Merchant-Id" = String, Header,
+ description = "Merchant ID of the profile.",
+ example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
+ ),
+ ),
request_body(
content = ProfileCreate,
examples(
@@ -169,7 +176,12 @@ pub async fn profile_create() {}
put,
path = "/v2/profiles/{profile_id}",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile")
+ ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ (
+ "X-Merchant-Id" = String, Header,
+ description = "Merchant ID of the profile.",
+ example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
+ ),
),
request_body(
content = ProfileCreate,
@@ -276,7 +288,12 @@ pub async fn routing_update_default_config() {}
get,
path = "/v2/profiles/{profile_id}",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile")
+ ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ (
+ "X-Merchant-Id" = String, Header,
+ description = "Merchant ID of the profile.",
+ example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
+ ),
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
@@ -339,6 +356,11 @@ pub async fn routing_retrieve_default_config() {}
path = "/v2/profiles/{profile_id}/connector_accounts",
params(
("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ (
+ "X-Merchant-Id" = String, Header,
+ description = "Merchant ID of the profile.",
+ example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
+ ),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
| 2024-10-11T09:36:55Z |
## Description
<!-- Describe your changes in detail -->
Add X-Merchant-Id to headers in Profile endpoints for v2
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
--> | 19a8474d8731ed7149b541f02ad237e30c4c9f24 | [
"api-reference-v2/openapi_spec.json",
"crates/openapi/src/routes/profile.rs"
] | ||
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 |
## 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)?
--> | 33bc83fce47c579457f1b9be0a91bb4fa13585ff | [
"crates/diesel_models/src/merchant_account.rs",
"crates/hyperswitch_domain_models/src/merchant_account.rs",
"crates/router/src/db/merchant_account.rs",
"docker-compose-development.yml"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6097 | Bug: [REFACTOR]: [TSYS] Add amount conversion framework to Tsys
### :memo: Feature Description
Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows.
Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application.
### :hammer: Possible Implementation
- For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly.
- Connectors should invoke the `convert` function to receive the amount in their required format.
- Refer to the [connector documentation](https://developers.tsys.com/api/product?key=Authentication+Platform) to determine the required amount format for each connector.
- You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context.
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [ ] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :package: Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/hyperswitch_connectors/src/connectors/tsys.rs b/crates/hyperswitch_connectors/src/connectors/tsys.rs
index ec53a99316f..25b47981def 100644
--- a/crates/hyperswitch_connectors/src/connectors/tsys.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys.rs
@@ -1,12 +1,11 @@
pub mod transformers;
-use std::fmt::Debug;
-
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
@@ -41,10 +40,18 @@ use hyperswitch_interfaces::{
use transformers as tsys;
use crate::{constants::headers, types::ResponseRouterData, utils};
+#[derive(Clone)]
+pub struct Tsys {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
-#[derive(Debug, Clone)]
-pub struct Tsys;
-
+impl Tsys {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
impl api::Payment for Tsys {}
impl api::PaymentSession for Tsys {}
impl api::ConnectorAccessToken for Tsys {}
@@ -156,7 +163,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = tsys::TsysPaymentsRequest::try_from(req)?;
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = tsys::TsysRouterData::from((amount, req));
+ let connector_req: transformers::TsysPaymentsRequest =
+ tsys::TsysPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -316,7 +330,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = tsys::TsysPaymentsCaptureRequest::try_from(req)?;
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+ let connector_router_data = tsys::TsysRouterData::from((amount, req));
+ let connector_req = tsys::TsysPaymentsCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -473,7 +493,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tsys {
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = tsys::TsysRefundRequest::try_from(req)?;
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = tsys::TsysRouterData::from((amount, req));
+
+ let connector_req = tsys::TsysRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
index e97cf228729..0e47edf294c 100644
--- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
@@ -1,4 +1,5 @@
use common_enums::enums;
+use common_utils::types::StringMinorUnit;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
@@ -7,13 +8,26 @@ use hyperswitch_domain_models::{
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
- RefundSyncRouterData, RefundsRouterData,
+ self, PaymentsCancelRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
+ RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
+pub struct TsysRouterData<T> {
+ pub amount: StringMinorUnit,
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for TsysRouterData<T> {
+ fn from((amount, router_data): (StringMinorUnit, T)) -> Self {
+ Self {
+ amount,
+ router_data,
+ }
+ }
+}
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
@@ -33,7 +47,7 @@ pub struct TsysPaymentAuthSaleRequest {
device_id: Secret<String>,
transaction_key: Secret<String>,
card_data_source: String,
- transaction_amount: String,
+ transaction_amount: StringMinorUnit,
currency_code: enums::Currency,
card_number: cards::CardNumber,
expiration_date: Secret<String>,
@@ -46,9 +60,12 @@ 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_data: &TsysRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let item = item_data.router_data.clone();
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => {
let connector_auth: TsysAuthType =
@@ -57,7 +74,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
card_data_source: "INTERNET".to_string(),
- transaction_amount: item.request.amount.to_string(),
+ transaction_amount: item_data.amount.clone(),
currency_code: item.request.currency,
card_number: ccard.card_number.clone(),
expiration_date: ccard
@@ -430,7 +447,7 @@ pub struct TsysCaptureRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
- transaction_amount: String,
+ transaction_amount: StringMinorUnit,
#[serde(rename = "transactionID")]
transaction_id: String,
#[serde(rename = "developerID")]
@@ -444,16 +461,19 @@ pub struct TsysPaymentsCaptureRequest {
capture: TsysCaptureRequest,
}
-impl TryFrom<&PaymentsCaptureRouterData> for TsysPaymentsCaptureRequest {
+impl TryFrom<&TsysRouterData<&types::PaymentsCaptureRouterData>> for TsysPaymentsCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item_data: &TsysRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let item = item_data.router_data.clone();
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let capture = TsysCaptureRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
transaction_id: item.request.connector_transaction_id.clone(),
developer_id: connector_auth.developer_id,
- transaction_amount: item.request.amount_to_capture.to_string(),
+ transaction_amount: item_data.amount.clone(),
};
Ok(Self { capture })
}
@@ -466,7 +486,7 @@ pub struct TsysReturnRequest {
#[serde(rename = "deviceID")]
device_id: Secret<String>,
transaction_key: Secret<String>,
- transaction_amount: String,
+ transaction_amount: StringMinorUnit,
#[serde(rename = "transactionID")]
transaction_id: String,
}
@@ -478,14 +498,15 @@ pub struct TsysRefundRequest {
return_request: TsysReturnRequest,
}
-impl<F> TryFrom<&RefundsRouterData<F>> for TsysRefundRequest {
+impl<F> TryFrom<&TsysRouterData<&RefundsRouterData<F>>> for TsysRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item_data: &TsysRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ let item = item_data.router_data;
let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?;
let return_request = TsysReturnRequest {
device_id: connector_auth.device_id,
transaction_key: connector_auth.transaction_key,
- transaction_amount: item.request.refund_amount.to_string(),
+ transaction_amount: item_data.amount.clone(),
transaction_id: item.request.connector_transaction_id.clone(),
};
Ok(Self { return_request })
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 5300e86afdb..8c953939831 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -508,7 +508,7 @@ impl ConnectorData {
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
- enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(&connector::Tsys))),
+ enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))),
enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))),
enums::Connector::Wellsfargo => {
diff --git a/crates/router/tests/connectors/tsys.rs b/crates/router/tests/connectors/tsys.rs
index 4cda0b479b2..6a4843ac2cd 100644
--- a/crates/router/tests/connectors/tsys.rs
+++ b/crates/router/tests/connectors/tsys.rs
@@ -16,7 +16,7 @@ impl utils::Connector for TsysTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Tsys;
utils::construct_connector_data_old(
- Box::new(&Tsys),
+ Box::new(Tsys::new()),
types::Connector::Tsys,
types::api::GetToken::Connector,
None,
| 2024-10-09T22:18:50Z |
## Description
added `StringMajorUnit` for amount conversion
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6097
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
--> | 3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1 | [
"crates/hyperswitch_connectors/src/connectors/tsys.rs",
"crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs",
"crates/router/src/types/api.rs",
"crates/router/tests/connectors/tsys.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6092 | Bug: [REFACTOR]: [MOLLIE] Add amount conversion framework to Mollie
### :memo: Feature Description
Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows.
Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application.
### :hammer: Possible Implementation
- For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly.
- Connectors should invoke the `convert` function to receive the amount in their required format.
- Refer to the [connector documentation](https://docs.mollie.com/reference/create-payment) to determine the required amount format for each connector.
- You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context.
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [ ] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :package: Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/hyperswitch_connectors/src/connectors/mollie.rs b/crates/hyperswitch_connectors/src/connectors/mollie.rs
index 5066fb422fa..010ae90c56f 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie.rs
@@ -1,12 +1,11 @@
pub mod transformers;
-use std::fmt::Debug;
-
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
@@ -43,10 +42,20 @@ use masking::{Mask, PeekInterface};
use transformers as mollie;
// use self::mollie::{webhook_headers, VoltWebhookBodyEventType};
-use crate::{constants::headers, types::ResponseRouterData};
+use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
+
+#[derive(Clone)]
+pub struct Mollie {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
+}
-#[derive(Debug, Clone)]
-pub struct Mollie;
+impl Mollie {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMajorUnitForConnector,
+ }
+ }
+}
impl api::Payment for Mollie {}
impl api::PaymentSession for Mollie {}
@@ -254,12 +263,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let router_obj = mollie::MollieRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
req.request.currency,
- req.request.amount,
- req,
- ))?;
+ )?;
+
+ let router_obj = mollie::MollieRouterData::from((amount, req));
let connector_req = mollie::MolliePaymentsRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -448,12 +458,13 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Mollie
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let router_obj = mollie::MollieRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
req.request.currency,
- req.request.refund_amount,
- req,
- ))?;
+ )?;
+
+ let router_obj = mollie::MollieRouterData::from((amount, req));
let connector_req = mollie::MollieRefundRequest::try_from(&router_obj)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
index a12434a460a..dc5f64bee18 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
@@ -1,6 +1,6 @@
use cards::CardNumber;
use common_enums::enums;
-use common_utils::{pii::Email, request::Method};
+use common_utils::{pii::Email, request::Method, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
@@ -8,7 +8,7 @@ use hyperswitch_domain_models::{
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types,
};
-use hyperswitch_interfaces::{api, errors};
+use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
@@ -17,7 +17,7 @@ use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
- self, AddressDetailsData, BrowserInformationData, CardData as CardDataUtil,
+ AddressDetailsData, BrowserInformationData, CardData as CardDataUtil,
PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData, RouterData as _,
},
};
@@ -26,26 +26,16 @@ type Error = error_stack::Report<errors::ConnectorError>;
#[derive(Debug, Serialize)]
pub struct MollieRouterData<T> {
- pub amount: String,
+ pub amount: StringMajorUnit,
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for MollieRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
-
- fn try_from(
- (currency_unit, currency, amount, router_data): (
- &api::CurrencyUnit,
- enums::Currency,
- i64,
- T,
- ),
- ) -> Result<Self, Self::Error> {
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
- Ok(Self {
+impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> {
+ fn from((amount, router_data): (StringMajorUnit, T)) -> Self {
+ Self {
amount,
router_data,
- })
+ }
}
}
@@ -68,7 +58,7 @@ pub struct MolliePaymentsRequest {
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct Amount {
currency: enums::Currency,
- value: String,
+ value: StringMajorUnit,
}
#[derive(Debug, Serialize)]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index e115558995d..ba2d6999f2b 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -434,7 +434,9 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new())))
}
enums::Connector::Klarna => Ok(ConnectorEnum::Old(Box::new(&connector::Klarna))),
- enums::Connector::Mollie => Ok(ConnectorEnum::Old(Box::new(&connector::Mollie))),
+ enums::Connector::Mollie => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new())))
+ }
enums::Connector::Nexixpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new())))
}
diff --git a/crates/router/tests/connectors/mollie.rs b/crates/router/tests/connectors/mollie.rs
index 7017363cad0..d59bc78226d 100644
--- a/crates/router/tests/connectors/mollie.rs
+++ b/crates/router/tests/connectors/mollie.rs
@@ -13,7 +13,7 @@ impl utils::Connector for MollieTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Mollie;
utils::construct_connector_data_old(
- Box::new(&Mollie),
+ Box::new(Mollie::new()),
types::Connector::Mollie,
types::api::GetToken::Connector,
None,
| 2024-10-09T18:52:03Z |
## Description
<!-- Describe your changes in detail -->
This PR do amount conversion changes for Mollie Connector and it accepts the amount in StringMajorUnit
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6092
## Test Cases
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1729161609",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"primary_business_details": [
{
"country": "US",
"business": "default"
},
{
"country": "GB",
"business": "payouts"
}
],
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://duck.com",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Create API key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729160602' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:__' \
--data '{
"name": "API Key 1",
"description": null,
"expiration": "2045-09-23T01:02:03.000Z"
}'
```
3. Create MCA for Mollie connector
```
curl --location 'http://localhost:8080/account/merchant_1729160602/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "mollie",
"connector_account_details":{
"auth_type":"HeaderKey",
"api_key":"_____________"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method" : "bank_transfer",
"payment_method_types":[
{
"payment_method_type":"sepa",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "przelewy24",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "bancontact_card",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "eps",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245"
},
"business_country": "US",
"business_label": "default"
}'
```
4. Create a Payment of Przelewy24 via Mollie
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ____' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "bank_redirect",
"payment_method_type": "przelewy24",
"payment_method_data": {
"bank_redirect": {
"przelewy24": {
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"profile_id": "pro_xA9ALBzKrljCM1SCCV26"
}'
```
Response
```
{
"payment_id": "pay_bEvdBi9AeDtAMvrSZi2J",
"merchant_id": "merchant_1729160602",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "mollie",
"client_secret": "pay_bEvdBi9AeDtAMvrSZi2J_secret_iv9QnUtPYFZbjeV0P7iW",
"created": "2024-10-17T10:25:07.604Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_redirect",
"payment_method_data": {
"bank_redirect": {
"type": "BankRedirectResponse",
"bank_name": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "BE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "BE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_bEvdBi9AeDtAMvrSZi2J/merchant_1729160602/pay_bEvdBi9AeDtAMvrSZi2J_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "przelewy24",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1729160707,
"expires": 1729164307,
"secret": "epk_7d82e37938e54484ab6baf8d22109af3"
},
"manual_retry_allowed": null,
"connector_transaction_id": "tr_fZzrHzunjU",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "tr_fZzrHzunjU",
"payment_link": null,
"profile_id": "pro_xA9ALBzKrljCM1SCCV26",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_WVDHef0DfuinnrZPKggd",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-17T10:40:07.604Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-17T10:25:09.587Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | edd099886da9c46800a646fe809796a08eb78c99 | [
"crates/hyperswitch_connectors/src/connectors/mollie.rs",
"crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs",
"crates/router/src/types/api.rs",
"crates/router/tests/connectors/mollie.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6237 | Bug: [REFACTOR]: (merchant_account_v2) move `organization_id` from request body to `headers`
When creating the merchant account, the request body is
```json
{
"merchant_name": "cloth_seller",
"organization_id": "org_tdhdTbv3z85XtxXGgVHS"
}
```
Here `organization_id` is the hierarchy_id / lineage id. This should be moved to a header called `X-Organization-Id`. Necessary changes have to be made in the handlers wherever this is affected. In this case only merchant account create would be affected. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index bd9de3a2962..9a406e9c733 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -453,6 +453,20 @@
"summary": "Merchant Account - Create",
"description": "Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.\n\nBefore creating the merchant account, it is mandatory to create an organization.",
"operationId": "Create a Merchant Account",
+ "parameters": [
+ {
+ "name": "X-Organization-Id",
+ "in": "header",
+ "description": "Organization ID for which the merchant account has to be created.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Organization-Id": "org_abcdefghijklmnop"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -466,8 +480,7 @@
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
},
- "merchant_name": "Cloth Store",
- "organization_id": "org_abcdefghijklmnop"
+ "merchant_name": "Cloth Store"
}
},
"Create a merchant account with metadata": {
@@ -476,14 +489,12 @@
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
- },
- "organization_id": "org_abcdefghijklmnop"
+ }
}
},
"Create a merchant account with minimal fields": {
"value": {
- "merchant_name": "Cloth Store",
- "organization_id": "org_abcdefghijklmnop"
+ "merchant_name": "Cloth Store"
}
}
}
@@ -9385,8 +9396,7 @@
"MerchantAccountCreate": {
"type": "object",
"required": [
- "merchant_name",
- "organization_id"
+ "merchant_name"
],
"properties": {
"merchant_name": {
@@ -9407,13 +9417,6 @@
"type": "object",
"description": "Metadata is useful for storing additional, unstructured information about the merchant account.",
"nullable": true
- },
- "organization_id": {
- "type": "string",
- "description": "The id of the organization to which the merchant belongs to. Please use the organization endpoint to create an organization",
- "example": "org_q98uSGAYbjEwqs0mJwnz",
- "maxLength": 64,
- "minLength": 1
}
},
"additionalProperties": false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 8f24bdf65bc..c9da386a11d 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -178,7 +178,8 @@ impl MerchantAccountCreate {
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
-pub struct MerchantAccountCreate {
+#[schema(as = MerchantAccountCreate)]
+pub struct MerchantAccountCreateWithoutOrgId {
/// Name of the Merchant Account, This will be used as a prefix to generate the id
#[schema(value_type= String, max_length = 64, example = "NewAge Retailer")]
pub merchant_name: Secret<common_utils::new_type::MerchantName>,
@@ -189,9 +190,17 @@ pub struct MerchantAccountCreate {
/// Metadata is useful for storing additional, unstructured information about the merchant account.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
+}
- /// The id of the organization to which the merchant belongs to. Please use the organization endpoint to create an organization
- #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
+// In v2 the struct used in the API is MerchantAccountCreateWithoutOrgId
+// The following struct is only used internally, so we can reuse the common
+// part of `create_merchant_account` without duplicating its code for v2
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, Serialize)]
+pub struct MerchantAccountCreate {
+ pub merchant_name: Secret<common_utils::new_type::MerchantName>,
+ pub merchant_details: Option<MerchantDetails>,
+ pub metadata: Option<pii::SecretSerdeValue>,
pub organization_id: id_type::OrganizationId,
}
diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rs
index f88a62daa1d..a83f35db1d8 100644
--- a/crates/common_utils/src/id_type/organization.rs
+++ b/crates/common_utils/src/id_type/organization.rs
@@ -1,3 +1,5 @@
+use crate::errors::{CustomResult, ValidationError};
+
crate::id_type!(
OrganizationId,
"A type for organization_id that can be used for organization ids"
@@ -13,3 +15,10 @@ crate::impl_generate_id_id_type!(OrganizationId, "org");
crate::impl_serializable_secret_id_type!(OrganizationId);
crate::impl_queryable_id_type!(OrganizationId);
crate::impl_to_sql_from_sql_id_type!(OrganizationId);
+
+impl OrganizationId {
+ /// Get an organization id from String
+ pub fn wrap(org_id: String) -> CustomResult<Self, ValidationError> {
+ Self::try_from(std::borrow::Cow::from(org_id))
+ }
+}
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 0a19c5a63c5..7bbe019dcba 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -154,7 +154,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
- api_models::admin::MerchantAccountCreate,
+ api_models::admin::MerchantAccountCreateWithoutOrgId,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs
index b92285245a4..01571da1de9 100644
--- a/crates/openapi/src/routes/merchant_account.rs
+++ b/crates/openapi/src/routes/merchant_account.rs
@@ -51,6 +51,13 @@ pub async fn merchant_account_create() {}
#[utoipa::path(
post,
path = "/v2/merchant_accounts",
+ params(
+ (
+ "X-Organization-Id" = String, Header,
+ description = "Organization ID for which the merchant account has to be created.",
+ example = json!({"X-Organization-Id": "org_abcdefghijklmnop"})
+ ),
+ ),
request_body(
content = MerchantAccountCreate,
examples(
@@ -58,7 +65,6 @@ pub async fn merchant_account_create() {}
"Create a merchant account with minimal fields" = (
value = json!({
"merchant_name": "Cloth Store",
- "organization_id": "org_abcdefghijklmnop"
})
)
),
@@ -66,7 +72,6 @@ pub async fn merchant_account_create() {}
"Create a merchant account with merchant details" = (
value = json!({
"merchant_name": "Cloth Store",
- "organization_id": "org_abcdefghijklmnop",
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
@@ -78,7 +83,6 @@ pub async fn merchant_account_create() {}
"Create a merchant account with metadata" = (
value = json!({
"merchant_name": "Cloth Store",
- "organization_id": "org_abcdefghijklmnop",
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 0eff78d38b4..06ab971925b 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -66,6 +66,7 @@ pub mod headers {
pub const X_API_VERSION: &str = "X-ApiVersion";
pub const X_FORWARDED_FOR: &str = "X-Forwarded-For";
pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
+ pub const X_ORGANIZATION_ID: &str = "X-Organization-Id";
pub const X_LOGIN: &str = "X-Login";
pub const X_TRANS_KEY: &str = "X-Trans-Key";
pub const X_VERSION: &str = "X-Version";
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 78238d3af07..16aebeabe73 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -95,7 +95,7 @@ pub async fn organization_retrieve(
.await
}
-#[cfg(feature = "olap")]
+#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))]
pub async fn merchant_account_create(
state: web::Data<AppState>,
@@ -115,6 +115,43 @@ pub async fn merchant_account_create(
.await
}
+#[cfg(all(feature = "olap", feature = "v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::MerchantsAccountCreate))]
+pub async fn merchant_account_create(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<api_models::admin::MerchantAccountCreateWithoutOrgId>,
+) -> HttpResponse {
+ let flow = Flow::MerchantsAccountCreate;
+ let headers = req.headers();
+
+ let org_id = match auth::HeaderMapStruct::new(headers).get_organization_id_from_header() {
+ Ok(org_id) => org_id,
+ Err(e) => return api::log_and_return_error_response(e),
+ };
+
+ // Converting from MerchantAccountCreateWithoutOrgId to MerchantAccountCreate so we can use the existing
+ // `create_merchant_account` function for v2 as well
+ let json_payload = json_payload.into_inner();
+ let new_request_payload_with_org_id = api_models::admin::MerchantAccountCreate {
+ merchant_name: json_payload.merchant_name,
+ merchant_details: json_payload.merchant_details,
+ metadata: json_payload.metadata,
+ organization_id: org_id,
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ new_request_payload_with_org_id,
+ |state, _, req, _| create_merchant_account(state, req),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
/// Merchant Account - Retrieve
///
/// Retrieve a merchant account details.
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b64c5d14f32..fa5041ab6b3 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -931,7 +931,7 @@ where
}
/// A helper struct to extract headers from the request
-struct HeaderMapStruct<'a> {
+pub(crate) struct HeaderMapStruct<'a> {
headers: &'a HeaderMap,
}
@@ -981,6 +981,18 @@ impl<'a> HeaderMapStruct<'a> {
)
})
}
+ #[cfg(feature = "v2")]
+ pub fn get_organization_id_from_header(&self) -> RouterResult<id_type::OrganizationId> {
+ self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID)
+ .map(|val| val.to_owned())
+ .and_then(|organization_id| {
+ id_type::OrganizationId::wrap(organization_id).change_context(
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID),
+ },
+ )
+ })
+ }
}
/// Get the merchant-id from `x-merchant-id` header
diff --git a/cypress-tests-v2/cypress/fixtures/merchant_account.json b/cypress-tests-v2/cypress/fixtures/merchant_account.json
index ac24e956513..dbe88ae10d4 100644
--- a/cypress-tests-v2/cypress/fixtures/merchant_account.json
+++ b/cypress-tests-v2/cypress/fixtures/merchant_account.json
@@ -1,7 +1,6 @@
{
"ma_create": {
- "merchant_name": "Hyperswitch Seller",
- "organization_id": ""
+ "merchant_name": "Hyperswitch Seller"
},
"ma_update": {
"merchant_name": "Hyperswitch"
diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js
index c9d1ef3f24f..abdf95194bb 100644
--- a/cypress-tests-v2/cypress/support/commands.js
+++ b/cypress-tests-v2/cypress/support/commands.js
@@ -173,15 +173,13 @@ Cypress.Commands.add(
.replaceAll(" ", "")
.toLowerCase();
- // Update request body
- merchantAccountCreateBody.organization_id = organization_id;
-
cy.request({
method: "POST",
url: url,
headers: {
"Content-Type": "application/json",
"api-key": api_key,
+ "X-Organization-Id": organization_id,
},
body: merchantAccountCreateBody,
failOnStatusCode: false,
| 2024-10-09T13:08:17Z |
## Description
<!-- Describe your changes in detail -->
For create_merchant request organization_id is currently being passed in request body. Moved it to request header
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1a. Correct Request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: org_55QZkS5H9AR8deTk9mRs' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
1b. Response
```json
{
"id": "clothsellerperson_iG5VNjsN9xuCg7Xx0uWh",
"merchant_name": "Cloth Seller Person",
"merchant_details": null,
"publishable_key": "pk_dev_1114028c68c242dc917bde0ec8fea75b",
"metadata": null,
"organization_id": "org_55QZkS5H9AR8deTk9mRs",
"recon_status": "not_requested"
}
```
2a. Non-existant Org-ID Request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: org_67ZZlS5H9AR8deTk8oPi' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
2b. Response
```json
{
"error": {
"type": "invalid_request",
"message": "organization with the given id does not exist",
"code": "IR_37"
}
}
```
3a. Invalid Org_id request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: I dont exist' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
3b. Response
```json
{
"error": {
"type": "invalid_request",
"message": "`X-Organization-Id` header is invalid",
"code": "IR_06"
}
}
```
## Cypress Screenshot:
<img width="1392" alt="image" src="https://github.com/user-attachments/assets/909b4754-b760-4850-adee-42786fa83614"> | c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0 |
1a. Correct Request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: org_55QZkS5H9AR8deTk9mRs' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
1b. Response
```json
{
"id": "clothsellerperson_iG5VNjsN9xuCg7Xx0uWh",
"merchant_name": "Cloth Seller Person",
"merchant_details": null,
"publishable_key": "pk_dev_1114028c68c242dc917bde0ec8fea75b",
"metadata": null,
"organization_id": "org_55QZkS5H9AR8deTk9mRs",
"recon_status": "not_requested"
}
```
2a. Non-existant Org-ID Request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: org_67ZZlS5H9AR8deTk8oPi' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
2b. Response
```json
{
"error": {
"type": "invalid_request",
"message": "organization with the given id does not exist",
"code": "IR_37"
}
}
```
3a. Invalid Org_id request
```
curl --location 'http://localhost:8080/v2/merchant_accounts' \
--header 'X-Organization-Id: I dont exist' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_name": "Cloth Seller Person"
}'
```
3b. Response
```json
{
"error": {
"type": "invalid_request",
"message": "`X-Organization-Id` header is invalid",
"code": "IR_06"
}
}
```
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/admin.rs",
"crates/common_utils/src/id_type/organization.rs",
"crates/openapi/src/openapi_v2.rs",
"crates/openapi/src/routes/merchant_account.rs",
"crates/router/src/lib.rs",
"crates/router/src/routes/admin.rs",
"crates/router/src/services/a... | |
juspay/hyperswitch | juspay__hyperswitch-6248 | Bug: [FEATURE]:[BILLWERK] Move connector code to hyperswitch_connectors
Connector code for Billwerk needs to be moved from crate router to new crate hyperswitch_connectors | diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index e5eaa22795a..ddd9fa861a6 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,4 +1,5 @@
pub mod bambora;
+pub mod billwerk;
pub mod bitpay;
pub mod cashtocode;
pub mod coinbase;
@@ -24,9 +25,10 @@ pub mod volt;
pub mod worldline;
pub use self::{
- bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
- cryptopay::Cryptopay, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal,
- fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim,
- mollie::Mollie, nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, square::Square,
- stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
+ bambora::Bambora, billwerk::Billwerk, bitpay::Bitpay, cashtocode::Cashtocode,
+ coinbase::Coinbase, cryptopay::Cryptopay, deutschebank::Deutschebank,
+ digitalvirgo::Digitalvirgo, dlocal::Dlocal, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu,
+ globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, novalnet::Novalnet,
+ powertranz::Powertranz, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys,
+ volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/billwerk.rs b/crates/hyperswitch_connectors/src/connectors/billwerk.rs
similarity index 66%
rename from crates/router/src/connector/billwerk.rs
rename to crates/hyperswitch_connectors/src/connectors/billwerk.rs
index 97106d511b8..251d2355f25 100644
--- a/crates/router/src/connector/billwerk.rs
+++ b/crates/hyperswitch_connectors/src/connectors/billwerk.rs
@@ -1,32 +1,55 @@
pub mod transformers;
+use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
-use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector};
-use error_stack::{report, ResultExt};
-use masking::PeekInterface;
-use transformers as billwerk;
-
-use super::utils::{
- RefundsRequestData, {self as connector_utils},
+use common_utils::{
+ consts::BASE64_ENGINE,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, RequestContent, Response,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{Mask, PeekInterface};
+use transformers::{
+ self as billwerk, BillwerkAuthType, BillwerkCaptureRequest, BillwerkErrorResponse,
+ BillwerkPaymentsRequest, BillwerkPaymentsResponse, BillwerkRefundRequest, BillwerkRouterData,
+ BillwerkTokenRequest, BillwerkTokenResponse,
+};
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{construct_not_implemented_error_report, convert_amount, RefundsRequestData},
+};
+
#[derive(Clone)]
pub struct Billwerk {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
@@ -39,7 +62,6 @@ impl Billwerk {
}
}
}
-
impl api::Payment for Billwerk {}
impl api::PaymentSession for Billwerk {}
impl api::ConnectorAccessToken for Billwerk {}
@@ -59,9 +81,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -85,17 +107,17 @@ impl ConnectorCommon for Billwerk {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.billwerk.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth = billwerk::BillwerkAuthType::try_from(auth_type)
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = BillwerkAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let encoded_api_key = consts::BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek()));
+ let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.peek()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
@@ -107,7 +129,7 @@ impl ConnectorCommon for Billwerk {
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: billwerk::BillwerkErrorResponse = res
+ let response: BillwerkErrorResponse = res
.response
.parse_struct("BillwerkErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -119,10 +141,8 @@ impl ConnectorCommon for Billwerk {
status_code: res.status_code,
code: response
.code
- .map_or(consts::NO_ERROR_CODE.to_string(), |code| code.to_string()),
- message: response
- .message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .map_or(NO_ERROR_CODE.to_string(), |code| code.to_string()),
+ message: response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: Some(response.error),
attempt_status: None,
connector_transaction_id: None,
@@ -141,44 +161,31 @@ impl ConnectorValidation for Billwerk {
common_enums::CaptureMethod::Automatic | common_enums::CaptureMethod::Manual => Ok(()),
common_enums::CaptureMethod::ManualMultiple
| common_enums::CaptureMethod::Scheduled => Err(
- super::utils::construct_not_implemented_error_report(capture_method, self.id()),
+ construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Billwerk {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Billwerk
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Billwerk {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Billwerk
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Billwerk
{
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Billwerk
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Billwerk
{
fn get_headers(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -188,8 +195,8 @@ impl
fn get_url(
&self,
- _req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
+ _req: &TokenizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = connectors
.billwerk
@@ -201,21 +208,21 @@ impl
fn get_request_body(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = billwerk::BillwerkTokenRequest::try_from(req)?;
+ let connector_req = BillwerkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
@@ -228,20 +235,20 @@ impl
fn handle_response(
&self,
- data: &types::TokenizationRouterData,
+ data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
- let response: billwerk::BillwerkTokenResponse = res
+ let response: BillwerkTokenResponse = res
.response
.parse_struct("BillwerkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -266,14 +273,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -283,36 +288,36 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/charge", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
- let connector_router_data = billwerk::BillwerkRouterData::try_from((amount, req))?;
- let connector_req = billwerk::BillwerkPaymentsRequest::try_from(&connector_router_data)?;
+ let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
+ let connector_req = BillwerkPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -329,17 +334,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: billwerk::BillwerkPaymentsResponse = res
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -363,14 +368,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -380,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/charge/{}",
@@ -392,12 +395,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -407,17 +410,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: billwerk::BillwerkPaymentsResponse = res
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: BillwerkPaymentsResponse = res
.response
.parse_struct("billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -441,14 +444,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -458,8 +459,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
@@ -470,28 +471,28 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
- let connector_router_data = billwerk::BillwerkRouterData::try_from((amount, req))?;
- let connector_req = billwerk::BillwerkCaptureRequest::try_from(&connector_router_data)?;
+ let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
+ let connector_req = BillwerkCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -506,17 +507,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: billwerk::BillwerkPaymentsResponse = res
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -540,14 +541,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -557,8 +556,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
@@ -569,12 +568,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -584,17 +583,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
- let response: billwerk::BillwerkPaymentsResponse = res
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: BillwerkPaymentsResponse = res
.response
.parse_struct("Billwerk BillwerkPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -618,14 +617,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Billwerk
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -635,35 +632,35 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
- let connector_router_data = billwerk::BillwerkRouterData::try_from((amount, req))?;
- let connector_req = billwerk::BillwerkRefundRequest::try_from(&connector_router_data)?;
+ let connector_router_data = BillwerkRouterData::try_from((amount, req))?;
+ let connector_req = BillwerkRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -678,17 +675,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: billwerk::RefundResponse = res
.response
.parse_struct("billwerk RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -712,12 +709,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Billwerk {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Billwerk {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -727,8 +724,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
@@ -739,12 +736,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -757,17 +754,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: billwerk::RefundResponse = res
.response
.parse_struct("billwerk RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -792,24 +789,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Billwerk {
+impl IncomingWebhook for Billwerk {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
similarity index 76%
rename from crates/router/src/connector/billwerk/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
index 6b21014cdd5..cc63e1ad7cc 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
@@ -1,16 +1,30 @@
+use common_enums::enums;
use common_utils::{
id_type,
pii::{Email, SecretSerdeValue},
types::MinorUnit,
};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
+ router_flow_types::{
+ payments,
+ refunds::{Execute, RSync},
+ },
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData},
- consts,
- core::errors,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{self, CardData as _, PaymentsAuthorizeRequestData, RouterData as _},
};
pub struct BillwerkRouterData<T> {
@@ -33,11 +47,11 @@ pub struct BillwerkAuthType {
pub(super) public_api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for BillwerkAuthType {
+impl TryFrom<&ConnectorAuthType> for BillwerkAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
public_api_key: key1.to_owned(),
}),
@@ -75,7 +89,7 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let connector_auth = &item.connector_auth_type;
let auth_type = BillwerkAuthType::try_from(connector_auth)?;
Ok(Self {
@@ -89,23 +103,23 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
strong_authentication_rule: None,
})
}
- domain::payments::PaymentMethodData::Wallet(_)
- | domain::payments::PaymentMethodData::CardRedirect(_)
- | domain::payments::PaymentMethodData::PayLater(_)
- | domain::payments::PaymentMethodData::BankRedirect(_)
- | domain::payments::PaymentMethodData::BankDebit(_)
- | domain::payments::PaymentMethodData::BankTransfer(_)
- | domain::payments::PaymentMethodData::Crypto(_)
- | domain::payments::PaymentMethodData::MandatePayment
- | domain::payments::PaymentMethodData::Reward
- | domain::payments::PaymentMethodData::RealTimePayment(_)
- | domain::payments::PaymentMethodData::Upi(_)
- | domain::payments::PaymentMethodData::Voucher(_)
- | domain::payments::PaymentMethodData::GiftCard(_)
- | domain::payments::PaymentMethodData::OpenBanking(_)
- | domain::payments::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("billwerk"),
)
@@ -123,25 +137,25 @@ pub struct BillwerkTokenResponse {
impl<T>
TryFrom<
- types::ResponseRouterData<
- api::PaymentMethodToken,
+ ResponseRouterData<
+ payments::PaymentMethodToken,
BillwerkTokenResponse,
T,
- types::PaymentsResponseData,
+ PaymentsResponseData,
>,
- > for types::RouterData<api::PaymentMethodToken, T, types::PaymentsResponseData>
+ > for RouterData<payments::PaymentMethodToken, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- api::PaymentMethodToken,
+ item: ResponseRouterData<
+ payments::PaymentMethodToken,
BillwerkTokenResponse,
T,
- types::PaymentsResponseData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id.expose(),
}),
..item.data
@@ -184,7 +198,7 @@ impl TryFrom<&BillwerkRouterData<&types::PaymentsAuthorizeRouterData>> for Billw
.into());
};
let source = match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(pm_token) => Ok(pm_token),
+ PaymentMethodToken::Token(pm_token) => Ok(pm_token),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_token",
}),
@@ -241,31 +255,25 @@ pub struct BillwerkPaymentsResponse {
error_state: Option<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BillwerkPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- BillwerkPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let error_response = if item.response.error.is_some() || item.response.error_state.is_some()
{
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: item
.response
.error_state
.clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ .unwrap_or(NO_ERROR_CODE.to_string()),
message: item
.response
.error_state
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: item.response.error,
status_code: item.http_code,
attempt_status: None,
@@ -274,8 +282,8 @@ impl<F, T>
} else {
None
};
- let payments_response = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.handle.clone()),
+ let payments_response = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -354,15 +362,15 @@ pub struct RefundResponse {
state: RefundState,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
@@ -371,15 +379,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.state),
}),
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 8a9d803a6f5..1e411ded76f 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -90,6 +90,7 @@ macro_rules! default_imp_for_authorize_session_token {
default_imp_for_authorize_session_token!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -130,6 +131,7 @@ macro_rules! default_imp_for_calculate_tax {
default_imp_for_calculate_tax!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -170,6 +172,7 @@ macro_rules! default_imp_for_session_update {
default_imp_for_session_update!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -212,6 +215,7 @@ macro_rules! default_imp_for_post_session_tokens {
default_imp_for_post_session_tokens!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Billwerk,
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
@@ -253,6 +257,7 @@ macro_rules! default_imp_for_complete_authorize {
}
default_imp_for_complete_authorize!(
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -291,6 +296,7 @@ macro_rules! default_imp_for_incremental_authorization {
default_imp_for_incremental_authorization!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -333,6 +339,7 @@ macro_rules! default_imp_for_create_customer {
default_imp_for_create_customer!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -375,6 +382,7 @@ macro_rules! default_imp_for_connector_redirect_response {
}
default_imp_for_connector_redirect_response!(
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -415,6 +423,7 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -456,6 +465,7 @@ macro_rules! default_imp_for_post_processing_steps{
default_imp_for_post_processing_steps!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -498,6 +508,7 @@ macro_rules! default_imp_for_approve {
default_imp_for_approve!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -540,6 +551,7 @@ macro_rules! default_imp_for_reject {
default_imp_for_reject!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -582,6 +594,7 @@ macro_rules! default_imp_for_webhook_source_verification {
default_imp_for_webhook_source_verification!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -625,6 +638,7 @@ macro_rules! default_imp_for_accept_dispute {
default_imp_for_accept_dispute!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -667,6 +681,7 @@ macro_rules! default_imp_for_submit_evidence {
default_imp_for_submit_evidence!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -709,6 +724,7 @@ macro_rules! default_imp_for_defend_dispute {
default_imp_for_defend_dispute!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -760,6 +776,7 @@ macro_rules! default_imp_for_file_upload {
default_imp_for_file_upload!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -804,6 +821,7 @@ macro_rules! default_imp_for_payouts_create {
#[cfg(feature = "payouts")]
default_imp_for_payouts_create!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -848,6 +866,7 @@ macro_rules! default_imp_for_payouts_retrieve {
#[cfg(feature = "payouts")]
default_imp_for_payouts_retrieve!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -892,6 +911,7 @@ macro_rules! default_imp_for_payouts_eligibility {
#[cfg(feature = "payouts")]
default_imp_for_payouts_eligibility!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -936,6 +956,7 @@ macro_rules! default_imp_for_payouts_fulfill {
#[cfg(feature = "payouts")]
default_imp_for_payouts_fulfill!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -980,6 +1001,7 @@ macro_rules! default_imp_for_payouts_cancel {
#[cfg(feature = "payouts")]
default_imp_for_payouts_cancel!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1024,6 +1046,7 @@ macro_rules! default_imp_for_payouts_quote {
#[cfg(feature = "payouts")]
default_imp_for_payouts_quote!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1068,6 +1091,7 @@ macro_rules! default_imp_for_payouts_recipient {
#[cfg(feature = "payouts")]
default_imp_for_payouts_recipient!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1112,6 +1136,7 @@ macro_rules! default_imp_for_payouts_recipient_account {
#[cfg(feature = "payouts")]
default_imp_for_payouts_recipient_account!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1156,6 +1181,7 @@ macro_rules! default_imp_for_frm_sale {
#[cfg(feature = "frm")]
default_imp_for_frm_sale!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1200,6 +1226,7 @@ macro_rules! default_imp_for_frm_checkout {
#[cfg(feature = "frm")]
default_imp_for_frm_checkout!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1244,6 +1271,7 @@ macro_rules! default_imp_for_frm_transaction {
#[cfg(feature = "frm")]
default_imp_for_frm_transaction!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1288,6 +1316,7 @@ macro_rules! default_imp_for_frm_fulfillment {
#[cfg(feature = "frm")]
default_imp_for_frm_fulfillment!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1332,6 +1361,7 @@ macro_rules! default_imp_for_frm_record_return {
#[cfg(feature = "frm")]
default_imp_for_frm_record_return!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1373,6 +1403,7 @@ macro_rules! default_imp_for_revoking_mandates {
default_imp_for_revoking_mandates!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 1c81db29d3f..54c0b6a8289 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -206,6 +206,7 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -249,6 +250,7 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -287,6 +289,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -331,6 +334,7 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -374,6 +378,7 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -417,6 +422,7 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -470,6 +476,7 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -515,6 +522,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -560,6 +568,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -605,6 +614,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -650,6 +660,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -695,6 +706,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -740,6 +752,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -785,6 +798,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -830,6 +844,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
#[cfg(feature = "payouts")]
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -873,6 +888,7 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -918,6 +934,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -963,6 +980,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1008,6 +1026,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1053,6 +1072,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1098,6 +1118,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
#[cfg(feature = "frm")]
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
@@ -1140,6 +1161,7 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
+ connectors::Billwerk,
connectors::Bitpay,
connectors::Cashtocode,
connectors::Coinbase,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 23b60d1cb1f..c0c64d76415 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -5,7 +5,6 @@ pub mod airwallex;
pub mod authorizedotnet;
pub mod bamboraapac;
pub mod bankofamerica;
-pub mod billwerk;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
@@ -57,11 +56,11 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
- coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
- deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal,
- fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
- globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
+ bambora, bambora::Bambora, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, cashtocode,
+ cashtocode::Cashtocode, coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay,
+ deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal,
+ dlocal::Dlocal, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu,
+ globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, square,
square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys,
tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline,
@@ -72,7 +71,7 @@ pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
- billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
+ bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 3ca620e9e81..4e900321f95 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -697,7 +697,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -770,7 +769,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -837,7 +835,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -926,7 +923,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -997,7 +993,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1052,7 +1047,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1134,7 +1128,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1296,7 +1289,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1370,7 +1362,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1444,7 +1435,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1518,7 +1508,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1592,7 +1581,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1666,7 +1654,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1740,7 +1727,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1814,7 +1800,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1886,7 +1871,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2048,7 +2032,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2122,7 +2105,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2196,7 +2178,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2270,7 +2251,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2344,7 +2324,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2415,7 +2394,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index eae41c91e4e..babf393bb3a 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -208,7 +208,6 @@ default_imp_for_complete_authorize!(
connector::Adyen,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Boku,
connector::Checkout,
connector::Datatrans,
@@ -279,7 +278,6 @@ default_imp_for_webhook_source_verification!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Braintree,
connector::Boku,
@@ -362,7 +360,6 @@ default_imp_for_create_customer!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -444,7 +441,6 @@ default_imp_for_connector_redirect_response!(
connector::Adyen,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Boku,
connector::Cybersource,
connector::Datatrans,
@@ -606,7 +602,6 @@ default_imp_for_accept_dispute!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -710,7 +705,6 @@ default_imp_for_file_upload!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -791,7 +785,6 @@ default_imp_for_submit_evidence!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -872,7 +865,6 @@ default_imp_for_defend_dispute!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -968,7 +960,6 @@ default_imp_for_pre_processing_steps!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1037,7 +1028,6 @@ default_imp_for_post_processing_steps!(
connector::Aci,
connector::Authorizedotnet,
connector::Bamboraapac,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1194,7 +1184,6 @@ default_imp_for_payouts_create!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1275,7 +1264,6 @@ default_imp_for_payouts_retrieve!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1361,7 +1349,6 @@ default_imp_for_payouts_eligibility!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1442,7 +1429,6 @@ default_imp_for_payouts_fulfill!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1520,7 +1506,6 @@ default_imp_for_payouts_cancel!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1602,7 +1587,6 @@ default_imp_for_payouts_quote!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1685,7 +1669,6 @@ default_imp_for_payouts_recipient!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1770,7 +1753,6 @@ default_imp_for_payouts_recipient_account!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1853,7 +1835,6 @@ default_imp_for_approve!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -1937,7 +1918,6 @@ default_imp_for_reject!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2112,7 +2092,6 @@ default_imp_for_frm_sale!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2196,7 +2175,6 @@ default_imp_for_frm_checkout!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2280,7 +2258,6 @@ default_imp_for_frm_transaction!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2364,7 +2341,6 @@ default_imp_for_frm_fulfillment!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2448,7 +2424,6 @@ default_imp_for_frm_record_return!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2530,7 +2505,6 @@ default_imp_for_incremental_authorization!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2610,7 +2584,6 @@ default_imp_for_revoking_mandates!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2850,7 +2823,6 @@ default_imp_for_authorize_session_token!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -2931,7 +2903,6 @@ default_imp_for_calculate_tax!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -3013,7 +2984,6 @@ default_imp_for_session_update!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
@@ -3094,7 +3064,6 @@ default_imp_for_post_session_tokens!(
connector::Authorizedotnet,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
| 2024-10-08T09:30:53Z |
## Description
<!-- Describe your changes in detail -->
Moved connector Billwerk from Router to HyperswitchConnector Trait
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
1. Create Merchant Account
```
curl --location 'http://localhost:8080/payments/pay_hY1WhQcAhKsQZehh2piy' \
--header 'Accept: application/json' \
--header 'api-key: ___'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728387984' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728387984/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "billwerk",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "___",
"key1": "___"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_QTQCvk4ajWvMAQ3GCqSKUCEN0p824XG0bRiK0APTwqIfqudd5LJ6E0wWTTLPhXqX' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 1337,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1337,
"customer_id": "customerg1",
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "340000000000009",
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"test": "ket"
}
}'
```
Response
```
{
"payment_id": "pay_hY1WhQcAhKsQZehh2piy",
"merchant_id": "merchant_1728387984",
"status": "succeeded",
"amount": 1337,
"net_amount": 1337,
"amount_capturable": 0,
"amount_received": 1337,
"connector": "billwerk",
"client_secret": "pay_hY1WhQcAhKsQZehh2piy_secret_fa5dFW8Pg6r42vmz7pMV",
"created": "2024-10-08T11:49:37.028Z",
"currency": "USD",
"customer_id": "customerg1",
"customer": {
"id": "customerg1",
"name": "John Doe",
"email": "guest2@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0009",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "340000",
"card_extended_bin": null,
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customerg1",
"created_at": 1728388177,
"expires": 1728391777,
"secret": "epk_c27ecfefd9d44b0dbaef1d1eb3a508dd"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pay_hY1WhQcAhKsQZehh2piy_1",
"frm_message": null,
"metadata": {
"test": "ket"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_hY1WhQcAhKsQZehh2piy_1",
"payment_link": null,
"profile_id": "pro_ekAp89eqFS6jdK6k6GZw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_yIpRQKAU7bI3M0ESckcy",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T12:04:37.028Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T11:49:39.050Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | 962afbd084458e9afb11a0278a8210edd9226a3d | 1. Create Merchant Account
```
curl --location 'http://localhost:8080/payments/pay_hY1WhQcAhKsQZehh2piy' \
--header 'Accept: application/json' \
--header 'api-key: ___'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728387984' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728387984/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "billwerk",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "___",
"key1": "___"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_QTQCvk4ajWvMAQ3GCqSKUCEN0p824XG0bRiK0APTwqIfqudd5LJ6E0wWTTLPhXqX' \
--header 'x-feature: router-custom' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 1337,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 1337,
"customer_id": "customerg1",
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "340000000000009",
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"test": "ket"
}
}'
```
Response
```
{
"payment_id": "pay_hY1WhQcAhKsQZehh2piy",
"merchant_id": "merchant_1728387984",
"status": "succeeded",
"amount": 1337,
"net_amount": 1337,
"amount_capturable": 0,
"amount_received": 1337,
"connector": "billwerk",
"client_secret": "pay_hY1WhQcAhKsQZehh2piy_secret_fa5dFW8Pg6r42vmz7pMV",
"created": "2024-10-08T11:49:37.028Z",
"currency": "USD",
"customer_id": "customerg1",
"customer": {
"id": "customerg1",
"name": "John Doe",
"email": "guest2@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0009",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "340000",
"card_extended_bin": null,
"card_exp_month": "12",
"card_exp_year": "2099",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest2@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customerg1",
"created_at": 1728388177,
"expires": 1728391777,
"secret": "epk_c27ecfefd9d44b0dbaef1d1eb3a508dd"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pay_hY1WhQcAhKsQZehh2piy_1",
"frm_message": null,
"metadata": {
"test": "ket"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_hY1WhQcAhKsQZehh2piy_1",
"payment_link": null,
"profile_id": "pro_ekAp89eqFS6jdK6k6GZw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_yIpRQKAU7bI3M0ESckcy",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T12:04:37.028Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T11:49:39.050Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
| [
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/billwerk.rs",
"crates/router/src/connector/billwerk/transformers.rs",
"crates/hyperswitch_connectors/src/default_implementations.rs",
"crates/hyperswitch_connectors/src/default_implementations_v2.rs",
"crates/router/src/connec... | |
juspay/hyperswitch | juspay__hyperswitch-6421 | Bug: feat(routing): add invalidate window as a service for SR based routing
add invalidate window as a service for SR based routing | diff --git a/config/development.toml b/config/development.toml
index 8f3ffdbcbb5..5a6a1250637 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -775,3 +775,7 @@ card_networks = "Visa, AmericanExpress, Mastercard"
[network_tokenization_supported_connectors]
connector_list = "cybersource"
+
+[grpc_client.dynamic_routing_client]
+host = "localhost"
+port = 7000
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index 0546d05ba7c..3264f065b51 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -14,8 +14,9 @@ use serde;
use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
CalSuccessRateRequest, CalSuccessRateResponse,
- CurrentBlockThreshold as DynamicCurrentThreshold, LabelWithStatus,
- UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
+ CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
+ InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig,
+ UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
use tonic::Status;
#[allow(
@@ -111,6 +112,11 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
+ /// To invalidates the success rate routing keys
+ async fn invalidate_success_rate_routing_keys(
+ &self,
+ id: String,
+ ) -> DynamicRoutingResult<InvalidateWindowsResponse>;
}
#[async_trait::async_trait]
@@ -139,9 +145,8 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
config,
});
- let mut client = self.clone();
-
- let response = client
+ let response = self
+ .clone()
.fetch_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
@@ -179,9 +184,8 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
config,
});
- let mut client = self.clone();
-
- let response = client
+ let response = self
+ .clone()
.update_success_rate_window(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
@@ -191,6 +195,23 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
Ok(response)
}
+
+ async fn invalidate_success_rate_routing_keys(
+ &self,
+ id: String,
+ ) -> DynamicRoutingResult<InvalidateWindowsResponse> {
+ let request = tonic::Request::new(InvalidateWindowsRequest { id });
+
+ let response = self
+ .clone()
+ .invalidate_windows(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to invalidate the success rate routing keys".to_string(),
+ ))?
+ .into_inner();
+ Ok(response)
+ }
}
impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 0bd38918ee7..f42bdb4af98 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -7,14 +7,17 @@ use api_models::{
routing::{self as routing_types, RoutingRetrieveQuery},
};
use async_trait::async_trait;
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use common_utils::ext_traits::AsyncExt;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting;
use hyperswitch_domain_models::{mandates, payment_address};
-#[cfg(feature = "v1")]
-use router_env::logger;
-use router_env::metrics::add_attributes;
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use router_env::{logger, metrics::add_attributes};
use rustc_hash::FxHashSet;
-#[cfg(feature = "v1")]
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use storage_impl::redis::cache;
#[cfg(feature = "payouts")]
@@ -1178,7 +1181,7 @@ pub async fn update_default_routing_config_for_profile(
))
}
-#[cfg(feature = "v1")]
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn toggle_success_based_routing(
state: SessionState,
merchant_account: domain::MerchantAccount,
@@ -1375,7 +1378,7 @@ pub async fn toggle_success_based_routing(
}
}
-#[cfg(feature = "v1")]
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn success_based_routing_update_configs(
state: SessionState,
request: routing_types::SuccessBasedRoutingConfig,
@@ -1445,6 +1448,27 @@ pub async fn success_based_routing_update_configs(
1,
&add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
);
+
+ let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id(
+ &state.tenant.redis_key_prefix,
+ profile_id.get_string_repr(),
+ );
+ state
+ .grpc_client
+ .dynamic_routing
+ .success_rate_client
+ .as_ref()
+ .async_map(|sr_client| async {
+ sr_client
+ .invalidate_success_rate_routing_keys(prefix_of_dynamic_routing_keys)
+ .await
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Failed to invalidate the routing keys".to_string(),
+ })
+ })
+ .await
+ .transpose()?;
+
Ok(service_api::ApplicationResponse::Json(new_record))
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index d747f96b9fb..e7f4385612d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1709,47 +1709,54 @@ impl Profile {
#[cfg(all(feature = "olap", feature = "v1"))]
impl Profile {
pub fn server(state: AppState) -> Scope {
- web::scope("/account/{account_id}/business_profile")
+ let mut route = web::scope("/account/{account_id}/business_profile")
.app_data(web::Data::new(state))
.service(
web::resource("")
.route(web::post().to(profiles::profile_create))
.route(web::get().to(profiles::profiles_list)),
- )
- .service(
- web::scope("/{profile_id}")
- .service(
- web::scope("/dynamic_routing").service(
- web::scope("/success_based")
- .service(
- web::resource("/toggle").route(
- web::post().to(routing::toggle_success_based_routing),
- ),
- )
- .service(web::resource("/config/{algorithm_id}").route(
- web::patch().to(|state, req, path, payload| {
- routing::success_based_routing_update_configs(
- state, req, path, payload,
- )
- }),
- )),
- ),
- )
- .service(
- web::resource("")
- .route(web::get().to(profiles::profile_retrieve))
- .route(web::post().to(profiles::profile_update))
- .route(web::delete().to(profiles::profile_delete)),
- )
- .service(
- web::resource("/toggle_extended_card_info")
- .route(web::post().to(profiles::toggle_extended_card_info)),
- )
- .service(
- web::resource("/toggle_connector_agnostic_mit")
- .route(web::post().to(profiles::toggle_connector_agnostic_mit)),
+ );
+
+ #[cfg(feature = "dynamic_routing")]
+ {
+ route =
+ route.service(
+ web::scope("/{profile_id}/dynamic_routing").service(
+ web::scope("/success_based")
+ .service(
+ web::resource("/toggle")
+ .route(web::post().to(routing::toggle_success_based_routing)),
+ )
+ .service(web::resource("/config/{algorithm_id}").route(
+ web::patch().to(|state, req, path, payload| {
+ routing::success_based_routing_update_configs(
+ state, req, path, payload,
+ )
+ }),
+ )),
),
- )
+ );
+ }
+
+ route = route.service(
+ web::scope("/{profile_id}")
+ .service(
+ web::resource("")
+ .route(web::get().to(profiles::profile_retrieve))
+ .route(web::post().to(profiles::profile_update))
+ .route(web::delete().to(profiles::profile_delete)),
+ )
+ .service(
+ web::resource("/toggle_extended_card_info")
+ .route(web::post().to(profiles::toggle_extended_card_info)),
+ )
+ .service(
+ web::resource("/toggle_connector_agnostic_mit")
+ .route(web::post().to(profiles::toggle_connector_agnostic_mit)),
+ ),
+ );
+
+ route
}
}
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index f0269bd029a..cf6d0371820 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -1013,7 +1013,7 @@ pub async fn routing_update_default_config_for_profile(
.await
}
-#[cfg(all(feature = "olap", feature = "v1"))]
+#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn toggle_success_based_routing(
state: web::Data<AppState>,
@@ -1056,7 +1056,7 @@ pub async fn toggle_success_based_routing(
.await
}
-#[cfg(all(feature = "olap", feature = "v1"))]
+#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn success_based_routing_update_configs(
state: web::Data<AppState>,
diff --git a/proto/success_rate.proto b/proto/success_rate.proto
index 8018f6d5fe4..38e56e36c0f 100644
--- a/proto/success_rate.proto
+++ b/proto/success_rate.proto
@@ -1,57 +1,68 @@
syntax = "proto3";
package success_rate;
- service SuccessRateCalculator {
- rpc FetchSuccessRate (CalSuccessRateRequest) returns (CalSuccessRateResponse);
-
- rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse);
- }
-
- // API-1 types
- message CalSuccessRateRequest {
- string id = 1;
- string params = 2;
- repeated string labels = 3;
- CalSuccessRateConfig config = 4;
- }
-
- message CalSuccessRateConfig {
- uint32 min_aggregates_size = 1;
- double default_success_rate = 2;
- }
-
- message CalSuccessRateResponse {
- repeated LabelWithScore labels_with_score = 1;
- }
-
- message LabelWithScore {
- double score = 1;
- string label = 2;
- }
+service SuccessRateCalculator {
+ rpc FetchSuccessRate (CalSuccessRateRequest) returns (CalSuccessRateResponse);
+
+ rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse);
+
+ rpc InvalidateWindows (InvalidateWindowsRequest) returns (InvalidateWindowsResponse);
+}
+
+// API-1 types
+message CalSuccessRateRequest {
+ string id = 1;
+ string params = 2;
+ repeated string labels = 3;
+ CalSuccessRateConfig config = 4;
+}
+
+message CalSuccessRateConfig {
+ uint32 min_aggregates_size = 1;
+ double default_success_rate = 2;
+}
+
+message CalSuccessRateResponse {
+ repeated LabelWithScore labels_with_score = 1;
+}
+
+message LabelWithScore {
+ double score = 1;
+ string label = 2;
+}
// API-2 types
- message UpdateSuccessRateWindowRequest {
- string id = 1;
- string params = 2;
- repeated LabelWithStatus labels_with_status = 3;
- UpdateSuccessRateWindowConfig config = 4;
- }
-
- message LabelWithStatus {
- string label = 1;
- bool status = 2;
- }
-
- message UpdateSuccessRateWindowConfig {
- uint32 max_aggregates_size = 1;
- CurrentBlockThreshold current_block_threshold = 2;
- }
-
- message CurrentBlockThreshold {
- optional uint64 duration_in_mins = 1;
- uint64 max_total_count = 2;
- }
-
- message UpdateSuccessRateWindowResponse {
- string message = 1;
- }
\ No newline at end of file
+message UpdateSuccessRateWindowRequest {
+ string id = 1;
+ string params = 2;
+ repeated LabelWithStatus labels_with_status = 3;
+ UpdateSuccessRateWindowConfig config = 4;
+}
+
+message LabelWithStatus {
+ string label = 1;
+ bool status = 2;
+}
+
+message UpdateSuccessRateWindowConfig {
+ uint32 max_aggregates_size = 1;
+ CurrentBlockThreshold current_block_threshold = 2;
+}
+
+message CurrentBlockThreshold {
+ optional uint64 duration_in_mins = 1;
+ uint64 max_total_count = 2;
+}
+
+message UpdateSuccessRateWindowResponse {
+ string message = 1;
+}
+
+ // API-3 types
+message InvalidateWindowsRequest {
+ string id = 1;
+}
+
+message InvalidateWindowsResponse {
+ string message = 1;
+}
\ No newline at end of file
| 2024-10-08T09:02:03Z |
## Description
add invalidate window as a service for SR based routing
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Hit the route, to update the config
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1730123706/business_profile/pro_TtvgDfAdgudrReoeeUJb/dynamic_routing/success_based/config/routing_lmPpwoTevEaYMVogesHs' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 8,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
- The old config would get invalidated
<img width="1725" alt="Screenshot 2024-10-28 at 11 25 13 PM" src="https://github.com/user-attachments/assets/54e9c142-9419-4e57-9bb9-36f92938c80a"> | f56d76ffec7ef6c27417a5df1999af7ccc3f1545 | - Hit the route, to update the config
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1730123706/business_profile/pro_TtvgDfAdgudrReoeeUJb/dynamic_routing/success_based/config/routing_lmPpwoTevEaYMVogesHs' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 8,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
- The old config would get invalidated
<img width="1725" alt="Screenshot 2024-10-28 at 11 25 13 PM" src="https://github.com/user-attachments/assets/54e9c142-9419-4e57-9bb9-36f92938c80a">
| [
"config/development.toml",
"crates/external_services/src/grpc_client/dynamic_routing.rs",
"crates/router/src/core/routing.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/routing.rs",
"proto/success_rate.proto"
] | |
juspay/hyperswitch | juspay__hyperswitch-6265 | Bug: [FEATURE]: [FORTE, NEXINETS, PAYEEZY, PAYU, ZEN] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for forte, nexinets, payeexy, payu and zen needs to be moved from crate router to new crate hyperswitch_connectors
### Possible Implementation
Connector code for forte, nexinets, payeezy, payu and zen needs to be moved from crate router to new crate hyperswitch_connectors
### 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 347d4e58797..9ccedba3c39 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3997,6 +3997,7 @@ dependencies = [
"hyperswitch_interfaces",
"image",
"masking",
+ "mime",
"once_cell",
"qrcode",
"rand",
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 21e5866aea0..5fc2fea9c8b 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -118,6 +118,10 @@ pub const CELL_IDENTIFIER_LENGTH: u8 = 5;
/// General purpose base64 engine
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
+
+/// URL Safe base64 engine
+pub const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose =
+ base64::engine::general_purpose::URL_SAFE;
/// Regex for matching a domain
/// Eg -
/// http://www.example.com
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index 2676f637223..86d6da446ee 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -20,6 +20,7 @@ error-stack = "0.4.1"
hex = "0.4.3"
http = "0.2.12"
image = { version = "0.25.1", default-features = false, features = ["png"] }
+mime = "0.3.17"
once_cell = "1.19.0"
qrcode = "0.14.0"
rand = "0.8.5"
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index ddd9fa861a6..3e8857e8d31 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -10,11 +10,15 @@ pub mod dlocal;
pub mod fiserv;
pub mod fiservemea;
pub mod fiuu;
+pub mod forte;
pub mod globepay;
pub mod helcim;
pub mod mollie;
+pub mod nexinets;
pub mod nexixpay;
pub mod novalnet;
+pub mod payeezy;
+pub mod payu;
pub mod powertranz;
pub mod square;
pub mod stax;
@@ -23,12 +27,14 @@ pub mod thunes;
pub mod tsys;
pub mod volt;
pub mod worldline;
+pub mod zen;
pub use self::{
bambora::Bambora, billwerk::Billwerk, bitpay::Bitpay, cashtocode::Cashtocode,
coinbase::Coinbase, cryptopay::Cryptopay, deutschebank::Deutschebank,
digitalvirgo::Digitalvirgo, dlocal::Dlocal, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu,
- globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, novalnet::Novalnet,
- powertranz::Powertranz, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys,
- volt::Volt, worldline::Worldline,
+ forte::Forte, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexinets::Nexinets,
+ nexixpay::Nexixpay, novalnet::Novalnet, payeezy::Payeezy, payu::Payu, powertranz::Powertranz,
+ square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt,
+ worldline::Worldline, zen::Zen,
};
diff --git a/crates/router/src/connector/forte.rs b/crates/hyperswitch_connectors/src/connectors/forte.rs
similarity index 69%
rename from crates/router/src/connector/forte.rs
rename to crates/hyperswitch_connectors/src/connectors/forte.rs
index 5ffa3a589c3..fd5c7792887 100644
--- a/crates/router/src/connector/forte.rs
+++ b/crates/hyperswitch_connectors/src/connectors/forte.rs
@@ -1,38 +1,55 @@
pub mod transformers;
+use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ consts::BASE64_ENGINE,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{report, ResultExt};
-use masking::PeekInterface;
-use transformers as forte;
-
-use super::utils::convert_amount;
-use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{PaymentsSyncRequestData, RefundsRequestData},
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts::NO_ERROR_CODE,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{Mask, PeekInterface};
+use transformers as forte;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{
+ construct_not_supported_error_report, convert_amount, PaymentsSyncRequestData,
+ RefundsRequestData,
},
- utils::BytesExt,
};
+
#[derive(Clone)]
pub struct Forte {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
@@ -59,12 +76,8 @@ impl api::RefundExecute for Forte {}
impl api::RefundSync for Forte {}
impl api::PaymentToken for Forte {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Forte
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Forte
{
}
pub const AUTH_ORG_ID_HEADER: &str = "X-Forte-Auth-Organization-Id";
@@ -75,9 +88,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let content_type = ConnectorCommon::common_get_content_type(self);
let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
common_headers.push((
@@ -97,14 +110,14 @@ impl ConnectorCommon for Forte {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.forte.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = forte::ForteAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let raw_basic_token = format!(
@@ -112,7 +125,7 @@ impl ConnectorCommon for Forte {
auth.api_access_id.peek(),
auth.api_secret_key.peek()
);
- let basic_token = format!("Basic {}", consts::BASE64_ENGINE.encode(raw_basic_token));
+ let basic_token = format!("Basic {}", BASE64_ENGINE.encode(raw_basic_token));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
@@ -141,7 +154,7 @@ impl ConnectorCommon for Forte {
let code = response
.response
.response_code
- .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string());
+ .unwrap_or_else(|| NO_ERROR_CODE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
@@ -163,38 +176,22 @@ impl ConnectorValidation for Forte {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Forte
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Forte {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Forte
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Forte {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Forte
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Forte {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Forte".to_string())
.into(),
@@ -202,14 +199,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Forte
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -219,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -233,8 +228,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -249,12 +244,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -271,10 +266,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsResponse = res
.response
.parse_struct("Forte AuthorizeResponse")
@@ -283,7 +278,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -299,14 +294,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Forte
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -316,8 +309,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
let txn_id = PaymentsSyncRequestData::get_connector_transaction_id(&req.request)
@@ -333,12 +326,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -347,10 +340,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: forte::FortePaymentsSyncResponse = res
.response
.parse_struct("forte PaymentsSyncResponse")
@@ -359,7 +352,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -375,14 +368,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Forte
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -392,8 +383,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -406,8 +397,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -415,12 +406,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Put)
+ RequestBuilder::new()
+ .method(Method::Put)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -435,10 +426,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: forte::ForteCaptureResponse = res
.response
.parse_struct("Forte PaymentsCaptureResponse")
@@ -447,7 +438,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -462,14 +453,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Forte
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -479,8 +468,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -493,8 +482,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -502,12 +491,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Put)
+ RequestBuilder::new()
+ .method(Method::Put)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -520,10 +509,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: forte::ForteCancelResponse = res
.response
.parse_struct("forte CancelResponse")
@@ -532,7 +521,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -548,12 +537,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Forte {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -563,8 +552,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -577,8 +566,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
@@ -593,11 +582,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -612,10 +601,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: forte::RefundResponse = res
.response
.parse_struct("forte RefundResponse")
@@ -624,7 +613,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -640,12 +629,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Forte {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Forte {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -655,8 +644,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
@@ -670,12 +659,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -685,10 +674,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: forte::RefundSyncResponse = res
.response
.parse_struct("forte RefundSyncResponse")
@@ -697,7 +686,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -714,24 +703,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Forte {
+impl IncomingWebhook for Forte {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
similarity index 79%
rename from crates/router/src/connector/forte/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
index 79b90d685ee..d04ea7bfee4 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
@@ -1,14 +1,24 @@
use cards::CardNumber;
+use common_enums::enums;
use common_utils::types::FloatMajorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{
- self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, RouterData,
+ types::{PaymentsCaptureResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, CardData as _PaymentsAuthorizeRequestData,
+ PaymentsAuthorizeRequestData, RouterData as _,
},
- core::errors,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom},
};
#[derive(Debug, Serialize)]
@@ -90,7 +100,7 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay
))?
}
match item.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
+ PaymentMethodData::Card(ref ccard) => {
let action = match item.request.is_auto_capture()? {
true => ForteAction::Sale,
false => ForteAction::Authorize,
@@ -120,23 +130,23 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay
card,
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
@@ -153,11 +163,11 @@ pub struct ForteAuthType {
pub(super) api_secret_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for ForteAuthType {
+impl TryFrom<&ConnectorAuthType> for ForteAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::MultiAuthKey {
+ ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
@@ -196,17 +206,15 @@ impl From<FortePaymentStatus> for enums::AttemptStatus {
}
}
-impl ForeignFrom<(ForteResponseCode, ForteAction)> for enums::AttemptStatus {
- fn foreign_from((response_code, action): (ForteResponseCode, ForteAction)) -> Self {
- match response_code {
- ForteResponseCode::A01 => match action {
- ForteAction::Authorize => Self::Authorized,
- ForteAction::Sale => Self::Pending,
- ForteAction::Verify => Self::Charged,
- },
- ForteResponseCode::A05 | ForteResponseCode::A06 => Self::Authorizing,
- _ => Self::Failure,
- }
+fn get_status(response_code: ForteResponseCode, action: ForteAction) -> enums::AttemptStatus {
+ match response_code {
+ ForteResponseCode::A01 => match action {
+ ForteAction::Authorize => enums::AttemptStatus::Authorized,
+ ForteAction::Sale => enums::AttemptStatus::Pending,
+ ForteAction::Verify => enums::AttemptStatus::Charged,
+ },
+ ForteResponseCode::A05 | ForteResponseCode::A06 => enums::AttemptStatus::Authorizing,
+ _ => enums::AttemptStatus::Failure,
}
}
@@ -277,21 +285,20 @@ 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<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, FortePaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, FortePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response_code = item.response.response.response_code;
let action = item.response.action;
let transaction_id = &item.response.transaction_id;
Ok(Self {
- status: enums::AttemptStatus::foreign_from((response_code, action)),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.to_string()),
+ status: get_status(response_code, action),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(serde_json::json!(ForteMeta {
@@ -323,24 +330,18 @@ 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<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- FortePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_id = &item.response.transaction_id;
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_id.to_string()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(serde_json::json!(ForteMeta {
@@ -398,18 +399,18 @@ pub struct ForteCaptureResponse {
pub response: CaptureResponseStatus,
}
-impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
+impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
for types::PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>,
+ item: 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(transaction_id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(serde_json::json!(ForteMeta {
@@ -466,19 +467,18 @@ 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<ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, ForteCancelResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, ForteCancelResponse, T, PaymentsResponseData>,
) -> 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(transaction_id.to_string()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(serde_json::json!(ForteMeta {
@@ -561,15 +561,15 @@ pub struct RefundResponse {
pub response: ResponseStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.response.response_code),
}),
@@ -584,15 +584,15 @@ pub struct RefundSyncResponse {
transaction_id: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>>
+ for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>,
+ item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
diff --git a/crates/router/src/connector/nexinets.rs b/crates/hyperswitch_connectors/src/connectors/nexinets.rs
similarity index 65%
rename from crates/router/src/connector/nexinets.rs
rename to crates/hyperswitch_connectors/src/connectors/nexinets.rs
index 113b2924fec..902afe34134 100644
--- a/crates/router/src/connector/nexinets.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexinets.rs
@@ -1,32 +1,53 @@
pub mod transformers;
-use std::fmt::Debug;
-
-use common_utils::request::RequestContent;
+use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use transformers as nexinets;
-
-use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{to_connector_meta, PaymentMethodDataType, PaymentsSyncRequestData},
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- storage::enums,
- ErrorResponse, Response,
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
+ RefundExecuteType, RefundSyncType, Response,
+ },
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::Mask;
+use transformers as nexinets;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{
+ construct_not_implemented_error_report, is_mandate_supported, to_connector_meta,
+ PaymentMethodDataType, PaymentsSyncRequestData,
},
- utils::BytesExt,
};
#[derive(Debug, Clone)]
@@ -60,9 +81,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -82,14 +103,14 @@ impl ConnectorCommon for Nexinets {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nexinets.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = nexinets::NexinetsAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -152,7 +173,7 @@ impl ConnectorValidation for Nexinets {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
@@ -160,7 +181,7 @@ impl ConnectorValidation for Nexinets {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
@@ -170,36 +191,22 @@ impl ConnectorValidation for Nexinets {
PaymentMethodDataType::Giropay,
PaymentMethodDataType::Ideal,
]);
- connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Nexinets
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nexinets {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Nexinets
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nexinets {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Nexinets
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Nexinets
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Nexinets".to_string())
.into(),
@@ -207,14 +214,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Nexinets
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -224,8 +229,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let url = if req.request.capture_method == Some(enums::CaptureMethod::Automatic) {
format!("{}/orders/debit", self.base_url(connectors))
@@ -237,8 +242,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -246,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -268,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPreAuthOrDebitResponse = res
.response
.parse_struct("Nexinets PaymentsAuthorizeResponse")
@@ -280,7 +281,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -296,14 +297,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Nexinets
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -313,8 +312,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
@@ -334,25 +333,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("nexinets NexinetsPaymentResponse")
@@ -361,7 +360,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -377,14 +376,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Nexinets
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -394,8 +391,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
@@ -409,8 +406,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -418,18 +415,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -438,10 +433,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
@@ -450,7 +445,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -466,14 +461,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Nexinets
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -483,8 +476,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
@@ -498,8 +491,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -507,16 +500,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsVoidType::get_request_body(
- self, req, connectors,
- )?)
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
@@ -524,10 +515,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
@@ -536,7 +527,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -552,14 +543,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Nexinets
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -569,8 +558,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_metadata.clone())?;
@@ -584,8 +573,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsRefundRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -593,29 +582,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets RefundResponse")
@@ -624,7 +609,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -640,12 +625,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nexinets {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nexinets {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -655,8 +640,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req
.request
@@ -674,25 +659,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets RefundSyncResponse")
@@ -701,7 +686,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -718,24 +703,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Nexinets {
+impl IncomingWebhook for Nexinets {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
@@ -743,12 +728,8 @@ impl api::IncomingWebhook for Nexinets {
impl api::PaymentToken for Nexinets {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Nexinets
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Nexinets
{
// Not Implemented (R)
}
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
similarity index 67%
rename from crates/router/src/connector/nexinets/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
index 6cf35f5d87d..eeb24233bef 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
@@ -1,20 +1,33 @@
use base64::Engine;
use cards::CardNumber;
-use common_utils::errors::CustomResult;
-use domain::PaymentMethodData;
+use common_enums::{enums, AttemptStatus};
+use common_utils::{consts, errors::CustomResult, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{
+ ApplePayWalletData, BankRedirectData, Card, PaymentMethodData, WalletData,
+ },
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{
+ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{
- self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, WalletData as _,
},
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom},
};
#[derive(Debug, Serialize)]
@@ -163,9 +176,9 @@ pub struct ApplepayPaymentMethod {
token_type: String,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
+impl TryFrom<&PaymentsAuthorizeRouterData> for NexinetsPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let return_url = item.request.router_return_url.clone();
let nexinets_async = NexinetsAsyncDetails {
success_url: return_url.clone(),
@@ -195,11 +208,11 @@ pub struct NexinetsAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for NexinetsAuthType {
+impl TryFrom<&ConnectorAuthType> for NexinetsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => {
+ ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(Self {
@@ -224,48 +237,48 @@ pub enum NexinetsPaymentStatus {
Aborted,
}
-impl ForeignFrom<(NexinetsPaymentStatus, NexinetsTransactionType)> for enums::AttemptStatus {
- fn foreign_from((status, method): (NexinetsPaymentStatus, NexinetsTransactionType)) -> Self {
- match status {
- NexinetsPaymentStatus::Success => match method {
- NexinetsTransactionType::Preauth => Self::Authorized,
- NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => Self::Charged,
- NexinetsTransactionType::Cancel => Self::Voided,
- },
- NexinetsPaymentStatus::Declined
- | NexinetsPaymentStatus::Failure
- | NexinetsPaymentStatus::Expired
- | NexinetsPaymentStatus::Aborted => match method {
- NexinetsTransactionType::Preauth => Self::AuthorizationFailed,
- NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
- Self::CaptureFailed
- }
- NexinetsTransactionType::Cancel => Self::VoidFailed,
- },
- NexinetsPaymentStatus::Ok => match method {
- NexinetsTransactionType::Preauth => Self::Authorized,
- _ => Self::Pending,
- },
- NexinetsPaymentStatus::Pending => Self::AuthenticationPending,
- NexinetsPaymentStatus::InProgress => Self::Pending,
- }
+fn get_status(status: NexinetsPaymentStatus, method: NexinetsTransactionType) -> AttemptStatus {
+ match status {
+ NexinetsPaymentStatus::Success => match method {
+ NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
+ NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
+ AttemptStatus::Charged
+ }
+ NexinetsTransactionType::Cancel => AttemptStatus::Voided,
+ },
+ NexinetsPaymentStatus::Declined
+ | NexinetsPaymentStatus::Failure
+ | NexinetsPaymentStatus::Expired
+ | NexinetsPaymentStatus::Aborted => match method {
+ NexinetsTransactionType::Preauth => AttemptStatus::AuthorizationFailed,
+ NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
+ AttemptStatus::CaptureFailed
+ }
+ NexinetsTransactionType::Cancel => AttemptStatus::VoidFailed,
+ },
+ NexinetsPaymentStatus::Ok => match method {
+ NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
+ _ => AttemptStatus::Pending,
+ },
+ NexinetsPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
+ NexinetsPaymentStatus::InProgress => AttemptStatus::Pending,
}
}
-impl TryFrom<&common_enums::enums::BankNames> for NexinetsBIC {
+impl TryFrom<&enums::BankNames> for NexinetsBIC {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(bank: &common_enums::enums::BankNames) -> Result<Self, Self::Error> {
+ fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> {
match bank {
- common_enums::enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
- common_enums::enums::BankNames::AsnBank => Ok(Self::AsnBank),
- common_enums::enums::BankNames::Bunq => Ok(Self::Bunq),
- common_enums::enums::BankNames::Ing => Ok(Self::Ing),
- common_enums::enums::BankNames::Knab => Ok(Self::Knab),
- common_enums::enums::BankNames::Rabobank => Ok(Self::Rabobank),
- common_enums::enums::BankNames::Regiobank => Ok(Self::Regiobank),
- common_enums::enums::BankNames::SnsBank => Ok(Self::SnsBank),
- common_enums::enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
- common_enums::enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
+ enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
+ enums::BankNames::AsnBank => Ok(Self::AsnBank),
+ enums::BankNames::Bunq => Ok(Self::Bunq),
+ enums::BankNames::Ing => Ok(Self::Ing),
+ enums::BankNames::Knab => Ok(Self::Knab),
+ enums::BankNames::Rabobank => Ok(Self::Rabobank),
+ enums::BankNames::Regiobank => Ok(Self::Regiobank),
+ enums::BankNames::SnsBank => Ok(Self::SnsBank),
+ enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
+ enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Nexinets".to_string(),
@@ -311,24 +324,12 @@ pub struct NexinetsPaymentsMetadata {
pub psync_flow: NexinetsTransactionType,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- NexinetsPreAuthOrDebitResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- NexinetsPreAuthOrDebitResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction = match item.response.transactions.first() {
Some(order) => order,
@@ -343,11 +344,11 @@ impl<F, T>
let redirection_data = item
.response
.redirect_url
- .map(|url| services::RedirectForm::from((url, services::Method::Get)));
+ .map(|url| RedirectForm::from((url, Method::Get)));
let resource_id = match item.response.transaction_type.clone() {
- NexinetsTransactionType::Preauth => types::ResponseId::NoResponseId,
+ NexinetsTransactionType::Preauth => ResponseId::NoResponseId,
NexinetsTransactionType::Debit => {
- types::ResponseId::ConnectorTransactionId(transaction.transaction_id.clone())
+ ResponseId::ConnectorTransactionId(transaction.transaction_id.clone())
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
@@ -355,17 +356,14 @@ impl<F, T>
.response
.payment_instrument
.payment_instrument_id
- .map(|id| types::MandateReference {
+ .map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
});
Ok(Self {
- status: enums::AttemptStatus::foreign_from((
- transaction.status.clone(),
- item.response.transaction_type,
- )),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ status: get_status(transaction.status.clone(), item.response.transaction_type),
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
@@ -393,9 +391,9 @@ pub struct NexinetsOrder {
pub order_id: String,
}
-impl TryFrom<&types::PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest {
+impl TryFrom<&PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.amount_to_capture,
currency: item.request.currency,
@@ -403,9 +401,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NexinetsCaptureOrVoidRequest
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest {
+impl TryFrom<&PaymentsCancelRouterData> for NexinetsCaptureOrVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.get_amount()?,
currency: item.request.get_currency()?,
@@ -423,13 +421,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<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, NexinetsPaymentResponse, T, types::PaymentsResponseData>,
+ item: 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 {
@@ -440,16 +437,13 @@ impl<F, T>
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
- types::ResponseId::ConnectorTransactionId(item.response.transaction_id)
+ ResponseId::ConnectorTransactionId(item.response.transaction_id)
}
- _ => types::ResponseId::NoResponseId,
+ _ => ResponseId::NoResponseId,
};
Ok(Self {
- status: enums::AttemptStatus::foreign_from((
- item.response.status,
- item.response.transaction_type,
- )),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
+ status: get_status(item.response.status, item.response.transaction_type),
+ response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: None,
mandate_reference: None,
@@ -473,9 +467,9 @@ pub struct NexinetsRefundRequest {
pub currency: enums::Currency,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for NexinetsRefundRequest {
+impl<F> TryFrom<&RefundsRouterData<F>> for NexinetsRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.request.refund_amount,
currency: item.request.currency,
@@ -521,15 +515,15 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, NexinetsRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, NexinetsRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, NexinetsRefundResponse>,
+ item: RefundsResponseRouterData<Execute, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -538,15 +532,15 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, NexinetsRefundRespon
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, NexinetsRefundResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, NexinetsRefundResponse>,
+ item: RefundsResponseRouterData<RSync, NexinetsRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -571,7 +565,7 @@ pub struct OrderErrorDetails {
}
fn get_payment_details_and_product(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PaymentsAuthorizeRouterData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
@@ -583,9 +577,9 @@ fn get_payment_details_and_product(
)),
PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?),
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
- domain::BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
- domain::BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
- domain::BankRedirectData::Ideal { bank_name, .. } => Ok((
+ BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
+ BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
+ BankRedirectData::Ideal { bank_name, .. } => Ok((
Some(NexinetsPaymentDetails::BankRedirects(Box::new(
NexinetsBankRedirects {
bic: bank_name
@@ -595,21 +589,21 @@ fn get_payment_details_and_product(
))),
NexinetsProduct::Ideal,
)),
- domain::BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
- domain::BankRedirectData::BancontactCard { .. }
- | domain::BankRedirectData::Blik { .. }
- | domain::BankRedirectData::Bizum { .. }
- | domain::BankRedirectData::Interac { .. }
- | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | domain::BankRedirectData::OnlineBankingFinland { .. }
- | domain::BankRedirectData::OnlineBankingPoland { .. }
- | domain::BankRedirectData::OnlineBankingSlovakia { .. }
- | domain::BankRedirectData::OpenBankingUk { .. }
- | domain::BankRedirectData::Przelewy24 { .. }
- | domain::BankRedirectData::Trustly { .. }
- | domain::BankRedirectData::OnlineBankingFpx { .. }
- | domain::BankRedirectData::OnlineBankingThailand { .. }
- | domain::BankRedirectData::LocalBankRedirect {} => {
+ BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
+ BankRedirectData::BancontactCard { .. }
+ | BankRedirectData::Blik { .. }
+ | BankRedirectData::Bizum { .. }
+ | BankRedirectData::Interac { .. }
+ | BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | BankRedirectData::OnlineBankingFinland { .. }
+ | BankRedirectData::OnlineBankingPoland { .. }
+ | BankRedirectData::OnlineBankingSlovakia { .. }
+ | BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::Przelewy24 { .. }
+ | BankRedirectData::Trustly { .. }
+ | BankRedirectData::OnlineBankingFpx { .. }
+ | BankRedirectData::OnlineBankingThailand { .. }
+ | BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
@@ -638,8 +632,8 @@ fn get_payment_details_and_product(
}
fn get_card_data(
- item: &types::PaymentsAuthorizeRouterData,
- card: &domain::payments::Card,
+ item: &PaymentsAuthorizeRouterData,
+ card: &Card,
) -> Result<NexinetsPaymentDetails, errors::ConnectorError> {
let (card_data, cof_contract) = match item.request.is_mandate_payment() {
true => {
@@ -666,10 +660,10 @@ fn get_card_data(
}
fn get_applepay_details(
- wallet_data: &domain::WalletData,
- applepay_data: &domain::ApplePayWalletData,
+ wallet_data: &WalletData,
+ applepay_data: &ApplePayWalletData,
) -> CustomResult<ApplePayDetails, errors::ConnectorError> {
- let payment_data = wallet_data.get_wallet_token_as_json("Apple Pay".to_string())?;
+ let payment_data = WalletData::get_wallet_token_as_json(wallet_data, "Apple Pay".to_string())?;
Ok(ApplePayDetails {
payment_data,
payment_method: ApplepayPaymentMethod {
@@ -681,9 +675,7 @@ fn get_applepay_details(
})
}
-fn get_card_details(
- req_card: &domain::payments::Card,
-) -> Result<CardDetails, errors::ConnectorError> {
+fn get_card_details(req_card: &Card) -> Result<CardDetails, errors::ConnectorError> {
Ok(CardDetails {
card_number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
@@ -693,14 +685,14 @@ fn get_card_details(
}
fn get_wallet_details(
- wallet: &domain::WalletData,
+ wallet: &WalletData,
) -> Result<
(Option<NexinetsPaymentDetails>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match wallet {
- domain::WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)),
- domain::WalletData::ApplePay(applepay_data) => Ok((
+ WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)),
+ WalletData::ApplePay(applepay_data) => Ok((
Some(NexinetsPaymentDetails::Wallet(Box::new(
NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details(
wallet,
@@ -709,32 +701,32 @@ fn get_wallet_details(
))),
NexinetsProduct::Applepay,
)),
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect { .. }
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect { .. }
- | domain::WalletData::VippsRedirect { .. }
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect { .. }
+ | WalletData::GooglePay(_)
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect { .. }
+ | WalletData::VippsRedirect { .. }
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
diff --git a/crates/router/src/connector/payeezy.rs b/crates/hyperswitch_connectors/src/connectors/payeezy.rs
similarity index 63%
rename from crates/router/src/connector/payeezy.rs
rename to crates/hyperswitch_connectors/src/connectors/payeezy.rs
index 5783cf1bc14..cb22d0cb7b0 100644
--- a/crates/router/src/connector/payeezy.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payeezy.rs
@@ -1,34 +1,49 @@
-mod transformers;
-
-use std::fmt::Debug;
+pub mod transformers;
+use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use common_enums::{CaptureMethod, PaymentMethodType};
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsVoidType, RefundExecuteType, Response,
+ },
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{ExposeInterface, Mask};
use rand::distributions::DistString;
use ring::hmac;
use transformers as payeezy;
use crate::{
- configs::settings,
- connector::utils as connector_utils,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::headers, types::ResponseRouterData, utils::construct_not_implemented_error_report,
};
#[derive(Debug, Clone)]
@@ -40,9 +55,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = payeezy::PayeezyAuthType::try_from(&req.connector_auth_type)?;
let request_payload = self
.get_request_body(req, connectors)?
@@ -66,7 +81,7 @@ where
let key = hmac::Key::new(hmac::HMAC_SHA256, auth.api_secret.expose().as_bytes());
let tag = hmac::sign(&key, signature_string.expose().as_bytes());
let hmac_sign = hex::encode(tag);
- let signature_value = consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign);
+ let signature_value = common_utils::consts::BASE64_ENGINE_URL_SAFE.encode(hmac_sign);
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -100,7 +115,7 @@ impl ConnectorCommon for Payeezy {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payeezy.base_url.as_ref()
}
@@ -138,14 +153,14 @@ impl ConnectorCommon for Payeezy {
impl ConnectorValidation for Payeezy {
fn validate_capture_method(
&self,
- capture_method: Option<enums::CaptureMethod>,
- _pmt: Option<enums::PaymentMethodType>,
+ capture_method: Option<CaptureMethod>,
+ _pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
- enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
- enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ CaptureMethod::Automatic | CaptureMethod::Manual => Ok(()),
+ CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err(
+ construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
@@ -154,22 +169,12 @@ impl ConnectorValidation for Payeezy {
impl api::Payment for Payeezy {}
impl api::MandateSetup for Payeezy {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Payeezy
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payeezy {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Payeezy".to_string())
.into(),
@@ -179,26 +184,20 @@ impl
impl api::PaymentToken for Payeezy {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Payeezy
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Payeezy
{
// Not Implemented (R)
}
impl api::PaymentVoid for Payeezy {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payeezy {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -208,8 +207,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -221,8 +220,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -230,27 +229,25 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsVoidType::get_request_body(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("Payeezy PaymentsResponse")
@@ -259,7 +256,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -278,27 +275,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
impl api::ConnectorAccessToken for Payeezy {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Payeezy
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payeezy {}
impl api::PaymentSync for Payeezy {}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payeezy {
// default implementation of build_request method will be executed
}
impl api::PaymentCapture for Payeezy {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payeezy {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -308,8 +298,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -321,8 +311,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = payeezy::PayeezyRouterData::try_from((
&self.get_currency_unit(),
@@ -337,17 +327,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -356,10 +344,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("Payeezy PaymentsResponse")
@@ -368,7 +356,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -387,22 +375,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
impl api::PaymentSession for Payeezy {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payeezy {
//TODO: implement sessions flow
}
impl api::PaymentAuthorize for Payeezy {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payeezy {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -412,16 +396,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = payeezy::PayeezyRouterData::try_from((
&self.get_currency_unit(),
@@ -436,19 +420,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -457,10 +437,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: payeezy::PayeezyPaymentsResponse = res
.response
.parse_struct("payeezy Response")
@@ -469,7 +449,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -490,14 +470,12 @@ impl api::Refund for Payeezy {}
impl api::RefundExecute for Payeezy {}
impl api::RefundSync for Payeezy {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Payeezy
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payeezy {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -507,8 +485,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -520,8 +498,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let router_obj = payeezy::PayeezyRouterData::try_from((
&self.get_currency_unit(),
@@ -535,28 +513,24 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
// Parse the response into a payeezy::RefundResponse
let response: payeezy::RefundResponse = res
.response
@@ -567,12 +541,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
router_env::logger::info!(connector_response=?response);
// Create a new instance of types::RefundsRouterData based on the response, input data, and HTTP code
- let response_data = types::ResponseRouterData {
+ let response_data = ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
};
- let router_data = types::RouterData::try_from(response_data)
+ let router_data = RouterData::try_from(response_data)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(router_data)
@@ -587,29 +561,29 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payeezy {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payeezy {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Payeezy {
+impl IncomingWebhook for Payeezy {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
similarity index 57%
rename from crates/router/src/connector/payeezy/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
index 685bf3c0fbb..47c5c40363e 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
@@ -1,32 +1,43 @@
use cards::CardNumber;
-use common_utils::ext_traits::Encode;
+use common_enums::{enums, AttemptStatus, CaptureMethod, Currency, PaymentMethod};
+use common_utils::{errors::ParsingError, ext_traits::Encode};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::Execute,
+ router_request_types::ResponseId,
+ router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{api::CurrencyUnit, errors::ConnectorError};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, CardData, RouterData},
- core::errors,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ get_amount_as_string, get_unimplemented_payment_method_error_message, to_connector_meta,
+ CardData, CardIssuer, RouterData as _,
+ },
};
+
#[derive(Debug, Serialize)]
pub struct PayeezyRouterData<T> {
pub amount: String,
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for PayeezyRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
+impl<T> TryFrom<(&CurrencyUnit, Currency, i64, T)> for PayeezyRouterData<T> {
+ type Error = error_stack::Report<ConnectorError>;
fn try_from(
- (currency_unit, currency, amount, router_data): (
- &api::CurrencyUnit,
- enums::Currency,
- i64,
- T,
- ),
+ (currency_unit, currency, amount, router_data): (&CurrencyUnit, Currency, i64, T),
) -> Result<Self, Self::Error> {
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
+ let amount = get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data,
@@ -53,20 +64,20 @@ pub enum PayeezyCardType {
Discover,
}
-impl TryFrom<utils::CardIssuer> for PayeezyCardType {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
+impl TryFrom<CardIssuer> for PayeezyCardType {
+ type Error = error_stack::Report<ConnectorError>;
+ fn try_from(issuer: CardIssuer) -> Result<Self, Self::Error> {
match issuer {
- utils::CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
- utils::CardIssuer::Master => Ok(Self::Mastercard),
- utils::CardIssuer::Discover => Ok(Self::Discover),
- utils::CardIssuer::Visa => Ok(Self::Visa),
-
- utils::CardIssuer::Maestro
- | utils::CardIssuer::DinersClub
- | utils::CardIssuer::JCB
- | utils::CardIssuer::CarteBlanche => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Payeezy"),
+ CardIssuer::AmericanExpress => Ok(Self::AmericanExpress),
+ CardIssuer::Master => Ok(Self::Mastercard),
+ CardIssuer::Discover => Ok(Self::Discover),
+ CardIssuer::Visa => Ok(Self::Visa),
+
+ CardIssuer::Maestro
+ | CardIssuer::DinersClub
+ | CardIssuer::JCB
+ | CardIssuer::CarteBlanche => Err(ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("Payeezy"),
))?,
}
}
@@ -118,36 +129,36 @@ pub enum Initiator {
CardHolder,
}
-impl TryFrom<&PayeezyRouterData<&types::PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
+impl TryFrom<&PayeezyRouterData<&PaymentsAuthorizeRouterData>> for PayeezyPaymentsRequest {
+ type Error = error_stack::Report<ConnectorError>;
fn try_from(
- item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &PayeezyRouterData<&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
- | 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::RealTimePayment
- | diesel_models::enums::PaymentMethod::Upi
- | diesel_models::enums::PaymentMethod::Voucher
- | diesel_models::enums::PaymentMethod::OpenBanking
- | diesel_models::enums::PaymentMethod::GiftCard => {
- Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
+ PaymentMethod::Card => get_card_specific_payment_data(item),
+
+ PaymentMethod::CardRedirect
+ | PaymentMethod::PayLater
+ | PaymentMethod::Wallet
+ | PaymentMethod::BankRedirect
+ | PaymentMethod::BankTransfer
+ | PaymentMethod::Crypto
+ | PaymentMethod::BankDebit
+ | PaymentMethod::Reward
+ | PaymentMethod::RealTimePayment
+ | PaymentMethod::Upi
+ | PaymentMethod::Voucher
+ | PaymentMethod::OpenBanking
+ | PaymentMethod::GiftCard => {
+ Err(ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
}
}
fn get_card_specific_payment_data(
- item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
-) -> Result<PayeezyPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
+ item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
+) -> Result<PayeezyPaymentsRequest, error_stack::Report<ConnectorError>> {
let merchant_ref = item.router_data.attempt_id.to_string();
let method = PayeezyPaymentMethodType::CreditCard;
let amount = item.amount.clone();
@@ -167,11 +178,9 @@ fn get_card_specific_payment_data(
})
}
fn get_transaction_type_and_stored_creds(
- item: &types::PaymentsAuthorizeRouterData,
-) -> Result<
- (PayeezyTransactionType, Option<StoredCredentials>),
- error_stack::Report<errors::ConnectorError>,
-> {
+ item: &PaymentsAuthorizeRouterData,
+) -> Result<(PayeezyTransactionType, Option<StoredCredentials>), error_stack::Report<ConnectorError>>
+{
let connector_mandate_id = item.request.mandate_id.as_ref().and_then(|mandate_ids| {
match mandate_ids.mandate_reference_id.clone() {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
@@ -203,36 +212,32 @@ fn get_transaction_type_and_stored_creds(
)
} else {
match item.request.capture_method {
- Some(diesel_models::enums::CaptureMethod::Manual) => {
- Ok((PayeezyTransactionType::Authorize, None))
- }
- Some(diesel_models::enums::CaptureMethod::Automatic) => {
- Ok((PayeezyTransactionType::Purchase, None))
+ Some(CaptureMethod::Manual) => Ok((PayeezyTransactionType::Authorize, None)),
+ Some(CaptureMethod::Automatic) => Ok((PayeezyTransactionType::Purchase, None)),
+
+ Some(CaptureMethod::ManualMultiple) | Some(CaptureMethod::Scheduled) | None => {
+ Err(ConnectorError::FlowNotSupported {
+ flow: item.request.capture_method.unwrap_or_default().to_string(),
+ connector: "Payeezy".to_string(),
+ })
}
-
- 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(),
- }),
}?
};
Ok((transaction_type, stored_credentials))
}
fn is_mandate_payment(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PaymentsAuthorizeRouterData,
connector_mandate_id: Option<&String>,
) -> bool {
item.request.setup_mandate_details.is_some() || connector_mandate_id.is_some()
}
fn get_payment_method_data(
- item: &PayeezyRouterData<&types::PaymentsAuthorizeRouterData>,
-) -> Result<PayeezyPaymentMethod, error_stack::Report<errors::ConnectorError>> {
+ item: &PayeezyRouterData<&PaymentsAuthorizeRouterData>,
+) -> Result<PayeezyPaymentMethod, error_stack::Report<ConnectorError>> {
match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref card) => {
+ PaymentMethodData::Card(ref card) => {
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
card_type,
@@ -247,25 +252,25 @@ fn get_payment_method_data(
Ok(PayeezyPaymentMethod::PayeezyCard(payeezy_card))
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Payeezy"),
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("Payeezy"),
))?
}
}
@@ -278,10 +283,10 @@ pub struct PayeezyAuthType {
pub(super) merchant_token: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+impl TryFrom<&ConnectorAuthType> for PayeezyAuthType {
+ type Error = error_stack::Report<ConnectorError>;
+ fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -293,7 +298,7 @@ impl TryFrom<&types::ConnectorAuthType> for PayeezyAuthType {
merchant_token: key1.to_owned(),
})
} else {
- Err(errors::ConnectorError::FailedToObtainAuthType.into())
+ Err(ConnectorError::FailedToObtainAuthType.into())
}
}
}
@@ -341,16 +346,12 @@ pub struct PayeezyCaptureOrVoidRequest {
currency_code: String,
}
-impl TryFrom<&PayeezyRouterData<&types::PaymentsCaptureRouterData>>
- for PayeezyCaptureOrVoidRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &PayeezyRouterData<&types::PaymentsCaptureRouterData>,
- ) -> Result<Self, Self::Error> {
+impl TryFrom<&PayeezyRouterData<&PaymentsCaptureRouterData>> for PayeezyCaptureOrVoidRequest {
+ type Error = error_stack::Report<ConnectorError>;
+ fn try_from(item: &PayeezyRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
- utils::to_connector_meta(item.router_data.request.connector_meta.clone())
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ to_connector_meta(item.router_data.request.connector_meta.clone())
+ .change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Capture,
amount: item.amount.clone(),
@@ -360,18 +361,18 @@ impl TryFrom<&PayeezyRouterData<&types::PaymentsCaptureRouterData>>
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+impl TryFrom<&PaymentsCancelRouterData> for PayeezyCaptureOrVoidRequest {
+ type Error = error_stack::Report<ConnectorError>;
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
- utils::to_connector_meta(item.request.connector_meta.clone())
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ to_connector_meta(item.request.connector_meta.clone())
+ .change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Void,
amount: item
.request
.amount
- .ok_or(errors::ConnectorError::RequestEncodingFailed)?
+ .ok_or(ConnectorError::RequestEncodingFailed)?
.to_string(),
currency_code: item.request.currency.unwrap_or_default().to_string(),
transaction_tag: metadata.transaction_tag,
@@ -397,39 +398,38 @@ pub struct PayeezyPaymentsMetadata {
transaction_tag: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PayeezyPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
- type Error = error_stack::Report<errors::ConnectorError>;
+ type Error = error_stack::Report<ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PayeezyPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let metadata = item
.response
.transaction_tag
.map(|txn_tag| construct_payeezy_payments_metadata(txn_tag).encode_to_value())
.transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)?;
+ .change_context(ConnectorError::ResponseHandlingFailed)?;
let mandate_reference = item
.response
.stored_credentials
.map(|credentials| credentials.cardbrand_original_transaction_id)
- .map(|id| types::MandateReference {
+ .map(|id| MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
mandate_metadata: None,
});
- let status = enums::AttemptStatus::foreign_from((
+ let status = get_status(
item.response.transaction_status,
item.response.transaction_type,
- ));
+ );
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: None,
@@ -449,26 +449,28 @@ impl<F, T>
}
}
-impl ForeignFrom<(PayeezyPaymentStatus, PayeezyTransactionType)> for enums::AttemptStatus {
- fn foreign_from((status, method): (PayeezyPaymentStatus, PayeezyTransactionType)) -> Self {
- match status {
- PayeezyPaymentStatus::Approved => match method {
- PayeezyTransactionType::Authorize => Self::Authorized,
- PayeezyTransactionType::Capture
- | PayeezyTransactionType::Purchase
- | PayeezyTransactionType::Recurring => Self::Charged,
- PayeezyTransactionType::Void => Self::Voided,
- PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending,
- },
- PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
- PayeezyTransactionType::Capture => Self::CaptureFailed,
- PayeezyTransactionType::Authorize
- | PayeezyTransactionType::Purchase
- | PayeezyTransactionType::Recurring => Self::AuthorizationFailed,
- PayeezyTransactionType::Void => Self::VoidFailed,
- PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => Self::Pending,
- },
- }
+fn get_status(status: PayeezyPaymentStatus, method: PayeezyTransactionType) -> AttemptStatus {
+ match status {
+ PayeezyPaymentStatus::Approved => match method {
+ PayeezyTransactionType::Authorize => AttemptStatus::Authorized,
+ PayeezyTransactionType::Capture
+ | PayeezyTransactionType::Purchase
+ | PayeezyTransactionType::Recurring => AttemptStatus::Charged,
+ PayeezyTransactionType::Void => AttemptStatus::Voided,
+ PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
+ AttemptStatus::Pending
+ }
+ },
+ PayeezyPaymentStatus::Declined | PayeezyPaymentStatus::NotProcessed => match method {
+ PayeezyTransactionType::Capture => AttemptStatus::CaptureFailed,
+ PayeezyTransactionType::Authorize
+ | PayeezyTransactionType::Purchase
+ | PayeezyTransactionType::Recurring => AttemptStatus::AuthorizationFailed,
+ PayeezyTransactionType::Void => AttemptStatus::VoidFailed,
+ PayeezyTransactionType::Refund | PayeezyTransactionType::Pending => {
+ AttemptStatus::Pending
+ }
+ },
}
}
@@ -482,14 +484,12 @@ pub struct PayeezyRefundRequest {
currency_code: String,
}
-impl<F> TryFrom<&PayeezyRouterData<&types::RefundsRouterData<F>>> for PayeezyRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &PayeezyRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+impl<F> TryFrom<&PayeezyRouterData<&RefundsRouterData<F>>> for PayeezyRefundRequest {
+ type Error = error_stack::Report<ConnectorError>;
+ fn try_from(item: &PayeezyRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let metadata: PayeezyPaymentsMetadata =
- utils::to_connector_meta(item.router_data.request.connector_metadata.clone())
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ to_connector_meta(item.router_data.request.connector_metadata.clone())
+ .change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
transaction_type: PayeezyTransactionType::Refund,
amount: item.amount.clone(),
@@ -538,15 +538,13 @@ pub struct RefundResponse {
pub gateway_message: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
- type Error = error_stack::Report<errors::ParsingError>;
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<ParsingError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.transaction_status),
}),
diff --git a/crates/router/src/connector/payu.rs b/crates/hyperswitch_connectors/src/connectors/payu.rs
similarity index 61%
rename from crates/router/src/connector/payu.rs
rename to crates/hyperswitch_connectors/src/connectors/payu.rs
index 4ff317d1f71..05f983b8fbb 100644
--- a/crates/router/src/connector/payu.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payu.rs
@@ -1,30 +1,49 @@
pub mod transformers;
-use std::fmt::Debug;
-
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use masking::PeekInterface;
-use transformers as payu;
-
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
- utils::BytesExt,
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
+ RefreshTokenType, RefundExecuteType, RefundSyncType, Response,
+ },
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{Mask, PeekInterface};
+use transformers as payu;
+
+use crate::{
+ constants::headers,
+ types::{RefreshTokenRouterData, ResponseRouterData},
+ utils::construct_not_supported_error_report,
};
#[derive(Debug, Clone)]
@@ -36,9 +55,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -67,14 +86,14 @@ impl ConnectorCommon for Payu {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payu.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = payu::PayuAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -85,7 +104,7 @@ impl ConnectorCommon for Payu {
fn build_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payu::PayuErrorResponse = res
@@ -117,7 +136,7 @@ impl ConnectorValidation for Payu {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ construct_not_supported_error_report(capture_method, self.id()),
),
}
}
@@ -126,22 +145,12 @@ impl ConnectorValidation for Payu {
impl api::Payment for Payu {}
impl api::MandateSetup for Payu {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Payu
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payu {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Payu".to_string())
.into(),
@@ -151,26 +160,20 @@ impl
impl api::PaymentToken for Payu {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Payu
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Payu
{
// Not Implemented (R)
}
impl api::PaymentVoid for Payu {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Payu
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -180,8 +183,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = &req.request.connector_transaction_id;
Ok(format!(
@@ -193,23 +196,23 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Delete)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Delete)
+ .url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: payu::PayuPaymentsCancelResponse = res
.response
.parse_struct("PaymentCancelResponse")
@@ -218,7 +221,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -227,7 +230,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -236,13 +239,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
impl api::ConnectorAccessToken for Payu {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Payu
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payu {
fn get_url(
&self,
- _req: &types::RefreshTokenRouterData,
- connectors: &settings::Connectors,
+ _req: &RefreshTokenRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -257,21 +258,19 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_headers(
&self,
- _req: &types::RefreshTokenRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RefreshTokenRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
- types::RefreshTokenType::get_content_type(self)
- .to_string()
- .into(),
+ RefreshTokenType::get_content_type(self).to_string().into(),
)])
}
fn get_request_body(
&self,
- req: &types::RefreshTokenRouterData,
- _connectors: &settings::Connectors,
+ req: &RefreshTokenRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuAuthUpdateRequest::try_from(req)?;
@@ -280,18 +279,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn build_request(
&self,
- req: &types::RefreshTokenRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefreshTokenRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.attach_default_headers()
- .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
- .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
- .set_body(types::RefreshTokenType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefreshTokenType::get_headers(self, req, connectors)?)
+ .url(&RefreshTokenType::get_url(self, req, connectors)?)
+ .set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
);
@@ -299,10 +296,10 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
}
fn handle_response(
&self,
- data: &types::RefreshTokenRouterData,
+ data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: payu::PayuAuthUpdateResponse = res
.response
.parse_struct("payu PayuAuthUpdateResponse")
@@ -311,7 +308,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -321,7 +318,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: payu::PayuAccessTokenErrorResponse = res
@@ -344,14 +341,12 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
}
impl api::PaymentSync for Payu {}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Payu
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -361,8 +356,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
@@ -379,32 +374,32 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: payu::PayuPaymentsSyncResponse = res
.response
.parse_struct("payu OrderResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -414,7 +409,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -422,14 +417,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
impl api::PaymentCapture for Payu {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Payu
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -439,8 +432,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}{}",
@@ -453,8 +446,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuPaymentsCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -462,18 +455,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Put)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Put)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -482,17 +473,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: payu::PayuPaymentsCaptureResponse = res
.response
.parse_struct("payu CaptureResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -502,7 +493,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -511,22 +502,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
impl api::PaymentSession for Payu {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Payu
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payu {
//TODO: implement sessions flow
}
impl api::PaymentAuthorize for Payu {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Payu
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -536,8 +523,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -548,8 +535,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -557,24 +544,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::RouterData<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -583,17 +562,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: payu::PayuPaymentsResponse = res
.response
.parse_struct("PayuPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -603,7 +582,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -614,12 +593,12 @@ impl api::Refund for Payu {}
impl api::RefundExecute for Payu {}
impl api::RefundSync for Payu {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payu {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -629,8 +608,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}{}",
@@ -643,8 +622,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payu::PayuRefundRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -652,36 +631,32 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: payu::RefundResponse = res
.response
.parse_struct("payu RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -691,19 +666,19 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payu {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payu {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -713,8 +688,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}{}",
@@ -727,32 +702,32 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: payu::RefundSyncResponse =
res.response
.parse_struct("payu RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -762,7 +737,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
@@ -770,24 +745,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Payu {
+impl IncomingWebhook for Payu {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
similarity index 82%
rename from crates/router/src/connector/payu/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
index 5365fc74ef2..7b3792c0e24 100644
--- a/crates/router/src/connector/payu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
@@ -1,14 +1,25 @@
use base64::Engine;
-use common_utils::pii::{Email, IpAddress};
+use common_enums::enums;
+use common_utils::{
+ consts::BASE64_ENGINE,
+ pii::{Email, IpAddress},
+};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{PaymentMethodData, WalletData},
+ router_data::{AccessToken, ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::AccessTokenRequestInfo,
- consts,
- core::errors,
- pii::Secret,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::AccessTokenRequestInfo as _,
};
const WALLET_IDENTIFIER: &str = "PBL";
@@ -70,7 +81,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let auth_type = PayuAuthType::try_from(&item.connector_auth_type)?;
let payment_method = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod {
+ PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Card(PayuCard::Card {
number: ccard.card_number,
expiration_month: ccard.card_exp_month,
@@ -78,19 +89,19 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
cvv: ccard.card_cvc,
}),
}),
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::GooglePay(data) => Ok(PayuPaymentMethod {
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::GooglePay(data) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Wallet({
PayuWallet {
value: PayuWalletCode::Ap,
wallet_type: WALLET_IDENTIFIER.to_string(),
authorization_code: Secret::new(
- consts::BASE64_ENGINE.encode(data.tokenization_data.token),
+ BASE64_ENGINE.encode(data.tokenization_data.token),
),
}
}),
}),
- domain::WalletData::ApplePay(data) => Ok(PayuPaymentMethod {
+ WalletData::ApplePay(data) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Wallet({
PayuWallet {
value: PayuWalletCode::Jp,
@@ -140,11 +151,11 @@ pub struct PayuAuthType {
pub(super) merchant_pos_id: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for PayuAuthType {
+impl TryFrom<&ConnectorAuthType> for PayuAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
api_key: api_key.to_owned(),
merchant_pos_id: key1.to_owned(),
}),
@@ -188,20 +199,17 @@ pub struct PayuPaymentsResponse {
pub ext_order_id: Option<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PayuPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PayuPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
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.clone(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -241,24 +249,17 @@ pub struct PayuPaymentsCaptureResponse {
status: PayuPaymentStatusData,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, PayuPaymentsCaptureResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- PayuPaymentsCaptureResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, PayuPaymentsCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -298,15 +299,15 @@ pub struct PayuAuthUpdateResponse {
pub grant_type: String,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, PayuAuthUpdateResponse, T, types::AccessToken>>
- for types::RouterData<F, T, types::AccessToken>
+impl<F, T> TryFrom<ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>>
+ for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PayuAuthUpdateResponse, T, types::AccessToken>,
+ item: ResponseRouterData<F, PayuAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::AccessToken {
+ response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
@@ -323,26 +324,17 @@ pub struct PayuPaymentsCancelResponse {
pub status: PayuPaymentStatusData,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, PayuPaymentsCancelResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- PayuPaymentsCancelResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, PayuPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
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.clone(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -457,18 +449,12 @@ pub struct PayuPaymentsSyncResponse {
properties: Option<Vec<PayuOrderResponseProperty>>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PayuPaymentsSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- PayuPaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let order = match item.response.orders.first() {
Some(order) => order,
@@ -476,8 +462,8 @@ impl<F, T>
};
Ok(Self {
status: enums::AttemptStatus::from(order.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(order.order_id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(order.order_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -569,16 +555,16 @@ pub struct RefundResponse {
refund: PayuRefundResponseData,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.refund.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.refund_id,
refund_status,
}),
@@ -591,19 +577,19 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
pub struct RefundSyncResponse {
refunds: Vec<PayuRefundResponseData>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>>
+ for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>,
+ item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
let refund = match item.response.refunds.first() {
Some(refund) => refund,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: refund.refund_id.clone(),
refund_status: enums::RefundStatus::from(refund.status.clone()),
}),
diff --git a/crates/router/src/connector/zen.rs b/crates/hyperswitch_connectors/src/connectors/zen.rs
similarity index 64%
rename from crates/router/src/connector/zen.rs
rename to crates/hyperswitch_connectors/src/connectors/zen.rs
index 2d522dbdf1b..a90b10fbd86 100644
--- a/crates/router/src/connector/zen.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen.rs
@@ -2,34 +2,52 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::{CallConnectorAction, PaymentAction};
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::{ByteSliceExt, BytesExt},
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as zen;
-use uuid::Uuid;
-
-use self::transformers::{ZenPaymentStatus, ZenWebhookTxnType};
-use crate::{
- configs::settings,
- consts,
- core::{
- errors::{self, CustomResult},
- payments,
+use hyperswitch_domain_models::{
+ api::ApplicationResponse,
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- domain, ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response},
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers::{self as zen, ZenPaymentStatus, ZenWebhookTxnType};
+use uuid::Uuid;
+
+use crate::{constants::headers, types::ResponseRouterData};
#[derive(Debug, Clone)]
pub struct Zen;
@@ -48,7 +66,7 @@ impl api::RefundExecute for Zen {}
impl api::RefundSync for Zen {}
impl Zen {
- fn get_default_header() -> (String, request::Maskable<String>) {
+ fn get_default_header() -> (String, masking::Maskable<String>) {
("request-id".to_string(), Uuid::new_v4().to_string().into())
}
}
@@ -59,9 +77,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -87,14 +105,14 @@ impl ConnectorCommon for Zen {
mime::APPLICATION_JSON.essence_str()
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.zen.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = zen::ZenAuthType::try_from(auth_type)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
@@ -120,13 +138,9 @@ impl ConnectorCommon for Zen {
code: response
.error
.clone()
- .map_or(consts::NO_ERROR_CODE.to_string(), |error| error.code),
+ .map_or(NO_ERROR_CODE.to_string(), |error| error.code),
message: response.error.map_or_else(
- || {
- response
- .message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string())
- },
+ || response.message.unwrap_or(NO_ERROR_MESSAGE.to_string()),
|error| error.message,
),
reason: None,
@@ -139,7 +153,7 @@ impl ConnectorCommon for Zen {
impl ConnectorValidation for Zen {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -149,58 +163,37 @@ impl ConnectorValidation for Zen {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Zen
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Zen {
//TODO: implement sessions flow
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Zen
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Zen
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Zen
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Zen {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Zen
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Zen {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Setup Mandate flow for Zen".to_string()).into())
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Zen
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Zen {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
let api_headers = match req.request.payment_method_data {
- domain::payments::PaymentMethodData::Wallet(_) => None,
+ PaymentMethodData::Wallet(_) => None,
_ => Some(Self::get_default_header()),
};
if let Some(api_header) = api_headers {
@@ -215,11 +208,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let endpoint = match &req.request.payment_method_data {
- domain::payments::PaymentMethodData::Wallet(_) => {
+ PaymentMethodData::Wallet(_) => {
let base_url = connectors
.zen
.secondary_base_url
@@ -234,8 +227,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = zen::ZenRouterData::try_from((
&self.get_currency_unit(),
@@ -249,20 +242,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -271,17 +260,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: zen::ZenPaymentsResponse = res
.response
.parse_struct("Zen PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -297,14 +286,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Zen
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Zen {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
headers.push(Self::get_default_header());
Ok(headers)
@@ -316,8 +303,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/transactions/merchant/{}",
@@ -328,32 +315,32 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: zen::ZenPaymentsResponse = res
.response
.parse_struct("zen PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -369,18 +356,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Zen
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Zen {
fn build_request(
&self,
- _req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_owned(),
connector: "Zen".to_owned(),
@@ -389,14 +370,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Zen
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Zen {
fn build_request(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Void".to_owned(),
connector: "Zen".to_owned(),
@@ -405,12 +384,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Zen {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Zen {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
headers.push(Self::get_default_header());
Ok(headers)
@@ -422,8 +401,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/transactions/refund",
@@ -433,8 +412,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = zen::ZenRouterData::try_from((
&self.get_currency_unit(),
@@ -448,29 +427,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: zen::RefundResponse = res
.response
.parse_struct("zen RefundResponse")
@@ -478,7 +453,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -494,12 +469,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Zen {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Zen {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
headers.push(Self::get_default_header());
Ok(headers)
@@ -511,8 +486,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v1/transactions/merchant/{}",
@@ -523,25 +498,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: zen::RefundResponse = res
.response
.parse_struct("zen RefundSyncResponse")
@@ -550,7 +525,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -567,17 +542,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Zen {
+impl IncomingWebhook for Zen {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: zen::ZenWebhookSignature = request
@@ -590,7 +565,7 @@ impl api::IncomingWebhook for Zen {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -610,7 +585,7 @@ impl api::IncomingWebhook for Zen {
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
@@ -641,7 +616,7 @@ impl api::IncomingWebhook for Zen {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: zen::ZenWebhookObjectReference = request
.body
@@ -663,8 +638,8 @@ impl api::IncomingWebhook for Zen {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: zen::ZenWebhookEventType = request
.body
.parse_struct("ZenWebhookEventType")
@@ -672,22 +647,22 @@ impl api::IncomingWebhook for Zen {
Ok(match &details.transaction_type {
ZenWebhookTxnType::TrtPurchase => match &details.status {
- ZenPaymentStatus::Rejected => api::IncomingWebhookEvent::PaymentIntentFailure,
- ZenPaymentStatus::Accepted => api::IncomingWebhookEvent::PaymentIntentSuccess,
+ ZenPaymentStatus::Rejected => IncomingWebhookEvent::PaymentIntentFailure,
+ ZenPaymentStatus::Accepted => IncomingWebhookEvent::PaymentIntentSuccess,
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
},
ZenWebhookTxnType::TrtRefund => match &details.status {
- ZenPaymentStatus::Rejected => api::IncomingWebhookEvent::RefundFailure,
- ZenPaymentStatus::Accepted => api::IncomingWebhookEvent::RefundSuccess,
+ ZenPaymentStatus::Rejected => IncomingWebhookEvent::RefundFailure,
+ ZenPaymentStatus::Accepted => IncomingWebhookEvent::RefundSuccess,
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
},
- ZenWebhookTxnType::Unknown => api::IncomingWebhookEvent::EventNotSupported,
+ ZenWebhookTxnType::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let reference_object: serde_json::Value = serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
@@ -695,29 +670,26 @@ impl api::IncomingWebhook for Zen {
}
fn get_webhook_api_response(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
- Ok(services::api::ApplicationResponse::Json(
- serde_json::json!({
- "status": "ok"
- }),
- ))
+ _request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
+ Ok(ApplicationResponse::Json(serde_json::json!({
+ "status": "ok"
+ })))
}
}
-impl services::ConnectorRedirectResponse for Zen {
+impl ConnectorRedirectResponse for Zen {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: PaymentAction,
+ ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ PaymentAction::PSync
+ | PaymentAction::CompleteAuthorize
+ | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(CallConnectorAction::Trigger)
}
}
}
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
similarity index 71%
rename from crates/router/src/connector/zen/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
index 799753fd52c..a564fb4ee60 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
@@ -1,20 +1,39 @@
use cards::CardNumber;
-use common_utils::{ext_traits::ValueExt, pii};
+use common_enums::enums;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::{OptionExt, ValueExt},
+ pii::{self},
+ request::Method,
+};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{
+ BankDebitData, BankRedirectData, BankTransferData, Card, CardRedirectData, GiftCardData,
+ PayLaterData, PaymentMethodData, VoucherData, WalletData,
+ },
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::{BrowserInformation, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{
+ api,
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+};
use masking::{ExposeInterface, PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use strum::Display;
use crate::{
- connector::utils::{
- self, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, RouterData,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, BrowserInformationData, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData,
+ RouterData as _,
},
- consts,
- core::errors::{self, CustomResult},
- services::{self, Method},
- types::{self, api, domain, storage::enums, transformers::ForeignTryFrom},
- utils::OptionExt,
};
#[derive(Debug, Serialize)]
@@ -41,10 +60,10 @@ pub struct ZenAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for ZenAuthType {
+impl TryFrom<&ConnectorAuthType> for ZenAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::HeaderKey { api_key } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
@@ -191,18 +210,10 @@ pub struct WalletSessionData {
pub pay_wall_secret: Option<Secret<String>>,
}
-impl
- TryFrom<(
- &ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::Card,
- )> for ZenPaymentsRequest
-{
+impl TryFrom<(&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card)> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: (
- &ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::Card,
- ),
+ value: (&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, ccard) = value;
let browser_info = item.router_data.request.get_browser_info()?;
@@ -245,14 +256,14 @@ impl
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::VoucherData,
+ &VoucherData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::VoucherData,
+ &VoucherData,
),
) -> Result<Self, Self::Error> {
let (item, voucher_data) = value;
@@ -266,20 +277,20 @@ impl
return_url: item.router_data.request.get_router_return_url()?,
});
let payment_channel = match voucher_data {
- domain::VoucherData::Boleto { .. } => ZenPaymentChannels::PclBoacompraBoleto,
- domain::VoucherData::Efecty => ZenPaymentChannels::PclBoacompraEfecty,
- domain::VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo,
- domain::VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra,
- domain::VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos,
- domain::VoucherData::Oxxo { .. }
- | domain::VoucherData::Alfamart { .. }
- | domain::VoucherData::Indomaret { .. }
- | domain::VoucherData::SevenEleven { .. }
- | domain::VoucherData::Lawson { .. }
- | domain::VoucherData::MiniStop { .. }
- | domain::VoucherData::FamilyMart { .. }
- | domain::VoucherData::Seicomart { .. }
- | domain::VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
+ VoucherData::Boleto { .. } => ZenPaymentChannels::PclBoacompraBoleto,
+ VoucherData::Efecty => ZenPaymentChannels::PclBoacompraEfecty,
+ VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo,
+ VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra,
+ VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos,
+ VoucherData::Oxxo { .. }
+ | VoucherData::Alfamart { .. }
+ | VoucherData::Indomaret { .. }
+ | VoucherData::SevenEleven { .. }
+ | VoucherData::Lawson { .. }
+ | VoucherData::MiniStop { .. }
+ | VoucherData::FamilyMart { .. }
+ | VoucherData::Seicomart { .. }
+ | VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?,
};
@@ -299,14 +310,14 @@ impl
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &Box<domain::BankTransferData>,
+ &Box<BankTransferData>,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &Box<domain::BankTransferData>,
+ &Box<BankTransferData>,
),
) -> Result<Self, Self::Error> {
let (item, bank_transfer_data) = value;
@@ -320,22 +331,22 @@ impl
return_url: item.router_data.request.get_router_return_url()?,
});
let payment_channel = match **bank_transfer_data {
- domain::BankTransferData::MultibancoBankTransfer { .. } => {
+ BankTransferData::MultibancoBankTransfer { .. } => {
ZenPaymentChannels::PclBoacompraMultibanco
}
- domain::BankTransferData::Pix { .. } => ZenPaymentChannels::PclBoacompraPix,
- domain::BankTransferData::Pse { .. } => ZenPaymentChannels::PclBoacompraPse,
- domain::BankTransferData::SepaBankTransfer { .. }
- | domain::BankTransferData::AchBankTransfer { .. }
- | domain::BankTransferData::BacsBankTransfer { .. }
- | domain::BankTransferData::PermataBankTransfer { .. }
- | domain::BankTransferData::BcaBankTransfer { .. }
- | domain::BankTransferData::BniVaBankTransfer { .. }
- | domain::BankTransferData::BriVaBankTransfer { .. }
- | domain::BankTransferData::CimbVaBankTransfer { .. }
- | domain::BankTransferData::DanamonVaBankTransfer { .. }
- | domain::BankTransferData::LocalBankTransfer { .. }
- | domain::BankTransferData::MandiriVaBankTransfer { .. } => {
+ BankTransferData::Pix { .. } => ZenPaymentChannels::PclBoacompraPix,
+ BankTransferData::Pse { .. } => ZenPaymentChannels::PclBoacompraPse,
+ BankTransferData::SepaBankTransfer { .. }
+ | BankTransferData::AchBankTransfer { .. }
+ | BankTransferData::BacsBankTransfer { .. }
+ | BankTransferData::PermataBankTransfer { .. }
+ | BankTransferData::BcaBankTransfer { .. }
+ | BankTransferData::BniVaBankTransfer { .. }
+ | BankTransferData::BriVaBankTransfer { .. }
+ | BankTransferData::CimbVaBankTransfer { .. }
+ | BankTransferData::DanamonVaBankTransfer { .. }
+ | BankTransferData::LocalBankTransfer { .. }
+ | BankTransferData::MandiriVaBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
@@ -437,14 +448,14 @@ impl
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::WalletData,
+ &WalletData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::WalletData,
+ &WalletData,
),
) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
@@ -453,7 +464,7 @@ impl
.parse_value("SessionObject")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let (specified_payment_channel, session_data) = match wallet_data {
- domain::WalletData::ApplePayRedirect(_) => (
+ WalletData::ApplePayRedirect(_) => (
ZenPaymentChannels::PclApplepay,
session
.apple_pay
@@ -461,7 +472,7 @@ impl
wallet_name: "Apple Pay".to_string(),
})?,
),
- domain::WalletData::GooglePayRedirect(_) => (
+ WalletData::GooglePayRedirect(_) => (
ZenPaymentChannels::PclGooglepay,
session
.google_pay
@@ -469,32 +480,32 @@ impl
wallet_name: "Google Pay".to_string(),
})?,
),
- domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::ApplePay(_)
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::WeChatPayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::ApplePay(_)
+ | WalletData::GooglePay(_)
+ | WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?,
};
@@ -625,7 +636,7 @@ fn get_item_object(
}
fn get_browser_details(
- browser_info: &types::BrowserInformation,
+ browser_info: &BrowserInformation,
) -> CustomResult<ZenBrowserDetails, errors::ConnectorError> {
let screen_height = browser_info
.screen_height
@@ -669,36 +680,28 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment
item: &ZenRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(card) => Self::try_from((item, card)),
- domain::PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
- domain::PaymentMethodData::Voucher(voucher_data) => {
- Self::try_from((item, voucher_data))
- }
- domain::PaymentMethodData::BankTransfer(bank_transfer_data) => {
+ PaymentMethodData::Card(card) => Self::try_from((item, card)),
+ PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
+ PaymentMethodData::Voucher(voucher_data) => Self::try_from((item, voucher_data)),
+ PaymentMethodData::BankTransfer(bank_transfer_data) => {
Self::try_from((item, bank_transfer_data))
}
- domain::PaymentMethodData::BankRedirect(bank_redirect_data) => {
+ PaymentMethodData::BankRedirect(bank_redirect_data) => {
Self::try_from(bank_redirect_data)
}
- domain::PaymentMethodData::PayLater(paylater_data) => Self::try_from(paylater_data),
- domain::PaymentMethodData::BankDebit(bank_debit_data) => {
- Self::try_from(bank_debit_data)
- }
- domain::PaymentMethodData::CardRedirect(car_redirect_data) => {
- Self::try_from(car_redirect_data)
- }
- domain::PaymentMethodData::GiftCard(gift_card_data) => {
- Self::try_from(gift_card_data.as_ref())
- }
- domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::PayLater(paylater_data) => Self::try_from(paylater_data),
+ PaymentMethodData::BankDebit(bank_debit_data) => Self::try_from(bank_debit_data),
+ PaymentMethodData::CardRedirect(car_redirect_data) => Self::try_from(car_redirect_data),
+ PaymentMethodData::GiftCard(gift_card_data) => Self::try_from(gift_card_data.as_ref()),
+ PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
@@ -707,28 +710,28 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment
}
}
-impl TryFrom<&domain::BankRedirectData> for ZenPaymentsRequest {
+impl TryFrom<&BankRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
- domain::BankRedirectData::Ideal { .. }
- | domain::BankRedirectData::Sofort { .. }
- | domain::BankRedirectData::BancontactCard { .. }
- | domain::BankRedirectData::Blik { .. }
- | domain::BankRedirectData::Trustly { .. }
- | domain::BankRedirectData::Eps { .. }
- | domain::BankRedirectData::Giropay { .. }
- | domain::BankRedirectData::Przelewy24 { .. }
- | domain::BankRedirectData::Bizum {}
- | domain::BankRedirectData::Interac { .. }
- | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | domain::BankRedirectData::OnlineBankingFinland { .. }
- | domain::BankRedirectData::OnlineBankingPoland { .. }
- | domain::BankRedirectData::OnlineBankingSlovakia { .. }
- | domain::BankRedirectData::OpenBankingUk { .. }
- | domain::BankRedirectData::OnlineBankingFpx { .. }
- | domain::BankRedirectData::OnlineBankingThailand { .. }
- | domain::BankRedirectData::LocalBankRedirect {} => {
+ BankRedirectData::Ideal { .. }
+ | BankRedirectData::Sofort { .. }
+ | BankRedirectData::BancontactCard { .. }
+ | BankRedirectData::Blik { .. }
+ | BankRedirectData::Trustly { .. }
+ | BankRedirectData::Eps { .. }
+ | BankRedirectData::Giropay { .. }
+ | BankRedirectData::Przelewy24 { .. }
+ | BankRedirectData::Bizum {}
+ | BankRedirectData::Interac { .. }
+ | BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | BankRedirectData::OnlineBankingFinland { .. }
+ | BankRedirectData::OnlineBankingPoland { .. }
+ | BankRedirectData::OnlineBankingSlovakia { .. }
+ | BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::OnlineBankingFpx { .. }
+ | BankRedirectData::OnlineBankingThailand { .. }
+ | BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
@@ -738,66 +741,60 @@ impl TryFrom<&domain::BankRedirectData> for ZenPaymentsRequest {
}
}
-impl TryFrom<&domain::payments::PayLaterData> for ZenPaymentsRequest {
+impl TryFrom<&PayLaterData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &domain::payments::PayLaterData) -> Result<Self, Self::Error> {
+ fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
- domain::payments::PayLaterData::KlarnaRedirect { .. }
- | domain::payments::PayLaterData::KlarnaSdk { .. }
- | domain::payments::PayLaterData::AffirmRedirect {}
- | domain::payments::PayLaterData::AfterpayClearpayRedirect { .. }
- | domain::payments::PayLaterData::PayBrightRedirect {}
- | domain::payments::PayLaterData::WalleyRedirect {}
- | domain::payments::PayLaterData::AlmaRedirect {}
- | domain::payments::PayLaterData::AtomeRedirect {} => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Zen"),
- )
- .into())
- }
+ PayLaterData::KlarnaRedirect { .. }
+ | PayLaterData::KlarnaSdk { .. }
+ | PayLaterData::AffirmRedirect {}
+ | PayLaterData::AfterpayClearpayRedirect { .. }
+ | PayLaterData::PayBrightRedirect {}
+ | PayLaterData::WalleyRedirect {}
+ | PayLaterData::AlmaRedirect {}
+ | PayLaterData::AtomeRedirect {} => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Zen"),
+ )
+ .into()),
}
}
}
-impl TryFrom<&domain::BankDebitData> for ZenPaymentsRequest {
+impl TryFrom<&BankDebitData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &domain::BankDebitData) -> Result<Self, Self::Error> {
+ fn try_from(value: &BankDebitData) -> Result<Self, Self::Error> {
match value {
- domain::BankDebitData::AchBankDebit { .. }
- | domain::BankDebitData::SepaBankDebit { .. }
- | domain::BankDebitData::BecsBankDebit { .. }
- | domain::BankDebitData::BacsBankDebit { .. } => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Zen"),
- )
- .into())
- }
+ BankDebitData::AchBankDebit { .. }
+ | BankDebitData::SepaBankDebit { .. }
+ | BankDebitData::BecsBankDebit { .. }
+ | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Zen"),
+ )
+ .into()),
}
}
}
-impl TryFrom<&domain::payments::CardRedirectData> for ZenPaymentsRequest {
+impl TryFrom<&CardRedirectData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &domain::payments::CardRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &CardRedirectData) -> Result<Self, Self::Error> {
match value {
- domain::payments::CardRedirectData::Knet {}
- | domain::payments::CardRedirectData::Benefit {}
- | domain::payments::CardRedirectData::MomoAtm {}
- | domain::payments::CardRedirectData::CardRedirect {} => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Zen"),
- )
- .into())
- }
+ CardRedirectData::Knet {}
+ | CardRedirectData::Benefit {}
+ | CardRedirectData::MomoAtm {}
+ | CardRedirectData::CardRedirect {} => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Zen"),
+ )
+ .into()),
}
}
}
-impl TryFrom<&domain::GiftCardData> for ZenPaymentsRequest {
+impl TryFrom<&GiftCardData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &domain::GiftCardData) -> Result<Self, Self::Error> {
+ fn try_from(value: &GiftCardData) -> Result<Self, Self::Error> {
match value {
- domain::GiftCardData::PaySafeCard {} | domain::GiftCardData::Givex(_) => {
+ GiftCardData::PaySafeCard {} | GiftCardData::Givex(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
@@ -879,29 +876,24 @@ pub struct ZenMerchantActionData {
redirect_url: url::Url,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, ZenPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, ZenPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, ZenPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, ZenPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
- ZenPaymentsResponse::ApiResponse(response) => {
- Self::try_from(types::ResponseRouterData {
- response,
- data: item.data,
- http_code: item.http_code,
- })
- }
- ZenPaymentsResponse::CheckoutResponse(response) => {
- Self::try_from(types::ResponseRouterData {
- response,
- data: item.data,
- http_code: item.http_code,
- })
- }
+ ZenPaymentsResponse::ApiResponse(response) => Self::try_from(ResponseRouterData {
+ response,
+ data: item.data,
+ http_code: item.http_code,
+ }),
+ ZenPaymentsResponse::CheckoutResponse(response) => Self::try_from(ResponseRouterData {
+ response,
+ data: item.data,
+ http_code: item.http_code,
+ }),
}
}
}
@@ -912,14 +904,14 @@ fn get_zen_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
let redirection_data_action = response.merchant_action.map(|merchant_action| {
(
- services::RedirectForm::from((merchant_action.data.redirect_url, Method::Get)),
+ RedirectForm::from((merchant_action.data.redirect_url, Method::Get)),
merchant_action.action,
)
});
@@ -929,14 +921,14 @@ fn get_zen_response(
};
let status = enums::AttemptStatus::foreign_try_from((response.status, action))?;
let error = if utils::is_payment_failure(status) {
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: response
.reject_code
- .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ .unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.reject_reason
.clone()
- .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.reject_reason,
status_code,
attempt_status: Some(status),
@@ -945,8 +937,8 @@ fn get_zen_response(
} else {
None
};
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(response.id.clone()),
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
@@ -958,12 +950,12 @@ fn get_zen_response(
Ok((status, error, payment_response_data))
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, ApiResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, ApiResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: types::ResponseRouterData<F, ApiResponse, T, types::PaymentsResponseData>,
+ value: ResponseRouterData<F, ApiResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) =
get_zen_response(value.response.clone(), value.http_code)?;
@@ -976,21 +968,21 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ApiResponse, T, types::PaymentsR
}
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, CheckoutResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: types::ResponseRouterData<F, CheckoutResponse, T, types::PaymentsResponseData>,
+ value: ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- let redirection_data = Some(services::RedirectForm::from((
+ let redirection_data = Some(RedirectForm::from((
value.response.redirect_url,
Method::Get,
)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data,
mandate_reference: None,
connector_metadata: None,
@@ -1054,12 +1046,12 @@ pub struct RefundResponse {
reject_reason: Option<String>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let (error, refund_response_data) = get_zen_refund_response(item.response, item.http_code)?;
Ok(Self {
@@ -1072,18 +1064,17 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
fn get_zen_refund_response(
response: RefundResponse,
status_code: u16,
-) -> CustomResult<(Option<types::ErrorResponse>, types::RefundsResponseData), errors::ConnectorError>
-{
+) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
let refund_status = enums::RefundStatus::from(response.status);
let error = if utils::is_refund_failure(refund_status) {
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: response
.reject_code
- .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ .unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.reject_reason
.clone()
- .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.reject_reason,
status_code,
attempt_status: None,
@@ -1092,23 +1083,21 @@ fn get_zen_refund_response(
} else {
None
};
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: response.id,
refund_status,
};
Ok((error, refund_response_data))
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 6c579977005..7ee75ddc4d1 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -1,6 +1,7 @@
/// Header Constants
pub(crate) mod headers {
pub(crate) const API_KEY: &str = "API-KEY";
+ pub(crate) const APIKEY: &str = "apikey";
pub(crate) const API_TOKEN: &str = "Api-Token";
pub(crate) const AUTHORIZATION: &str = "Authorization";
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
@@ -8,7 +9,9 @@ pub(crate) mod headers {
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature";
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
+ pub(crate) const NONCE: &str = "nonce";
pub(crate) const TIMESTAMP: &str = "Timestamp";
+ pub(crate) const TOKEN: &str = "token";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 1e411ded76f..abdaf1e92c4 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -101,10 +101,14 @@ default_imp_for_authorize_session_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -112,7 +116,8 @@ default_imp_for_authorize_session_token!(
connectors::Volt,
connectors::Thunes,
connectors::Tsys,
- connectors::Worldline
+ connectors::Worldline,
+ connectors::Zen
);
macro_rules! default_imp_for_calculate_tax {
@@ -140,15 +145,20 @@ default_imp_for_calculate_tax!(
connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
+ connectors::Forte,
connectors::Helcim,
connectors::Stax,
connectors::Square,
connectors::Novalnet,
connectors::Mollie,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Fiuu,
connectors::Globepay,
connectors::Worldline,
+ connectors::Zen,
connectors::Powertranz,
connectors::Thunes,
connectors::Tsys,
@@ -181,16 +191,21 @@ default_imp_for_session_update!(
connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
+ connectors::Forte,
connectors::Helcim,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Mollie,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Fiuu,
connectors::Globepay,
connectors::Worldline,
+ connectors::Zen,
connectors::Powertranz,
connectors::Thunes,
connectors::Tsys,
@@ -224,12 +239,16 @@ default_imp_for_post_session_tokens!(
connectors::Square,
connectors::Fiserv,
connectors::Fiservemea,
+ connectors::Forte,
connectors::Helcim,
connectors::Stax,
connectors::Taxjar,
connectors::Mollie,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Fiuu,
connectors::Globepay,
connectors::Worldline,
@@ -237,7 +256,8 @@ default_imp_for_post_session_tokens!(
connectors::Thunes,
connectors::Tsys,
connectors::Deutschebank,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
use crate::connectors;
@@ -267,16 +287,21 @@ default_imp_for_complete_authorize!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Stax,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_incremental_authorization {
@@ -307,10 +332,14 @@ default_imp_for_incremental_authorization!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -319,7 +348,8 @@ default_imp_for_incremental_authorization!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_create_customer {
@@ -350,18 +380,23 @@ default_imp_for_create_customer!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Mollie,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_connector_redirect_response {
@@ -393,9 +428,13 @@ default_imp_for_connector_redirect_response!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Stax,
connectors::Square,
@@ -434,9 +473,13 @@ default_imp_for_pre_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -445,7 +488,8 @@ default_imp_for_pre_processing_steps!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_post_processing_steps{
@@ -476,10 +520,14 @@ default_imp_for_post_processing_steps!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -488,7 +536,8 @@ default_imp_for_post_processing_steps!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_approve {
@@ -519,10 +568,14 @@ default_imp_for_approve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -531,7 +584,8 @@ default_imp_for_approve!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_reject {
@@ -562,10 +616,14 @@ default_imp_for_reject!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -574,7 +632,8 @@ default_imp_for_reject!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_webhook_source_verification {
@@ -605,10 +664,14 @@ default_imp_for_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -617,7 +680,8 @@ default_imp_for_webhook_source_verification!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_accept_dispute {
@@ -649,10 +713,14 @@ default_imp_for_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -661,7 +729,8 @@ default_imp_for_accept_dispute!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_submit_evidence {
@@ -692,10 +761,14 @@ default_imp_for_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -704,7 +777,8 @@ default_imp_for_submit_evidence!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_defend_dispute {
@@ -735,10 +809,14 @@ default_imp_for_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -747,7 +825,8 @@ default_imp_for_defend_dispute!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_file_upload {
@@ -787,10 +866,14 @@ default_imp_for_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -799,7 +882,8 @@ default_imp_for_file_upload!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -832,10 +916,14 @@ default_imp_for_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -844,7 +932,8 @@ default_imp_for_payouts_create!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -877,10 +966,14 @@ default_imp_for_payouts_retrieve!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -889,7 +982,8 @@ default_imp_for_payouts_retrieve!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -922,10 +1016,14 @@ default_imp_for_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -934,7 +1032,8 @@ default_imp_for_payouts_eligibility!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -967,10 +1066,14 @@ default_imp_for_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -979,7 +1082,8 @@ default_imp_for_payouts_fulfill!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -1012,10 +1116,14 @@ default_imp_for_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1024,7 +1132,8 @@ default_imp_for_payouts_cancel!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -1057,10 +1166,14 @@ default_imp_for_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1069,7 +1182,8 @@ default_imp_for_payouts_quote!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -1102,10 +1216,14 @@ default_imp_for_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1114,7 +1232,8 @@ default_imp_for_payouts_recipient!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -1147,10 +1266,14 @@ default_imp_for_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1159,7 +1282,8 @@ default_imp_for_payouts_recipient_account!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1192,10 +1316,14 @@ default_imp_for_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1204,7 +1332,8 @@ default_imp_for_frm_sale!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1237,10 +1366,14 @@ default_imp_for_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1249,7 +1382,8 @@ default_imp_for_frm_checkout!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1282,10 +1416,14 @@ default_imp_for_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1294,7 +1432,8 @@ default_imp_for_frm_transaction!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1327,10 +1466,14 @@ default_imp_for_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1339,7 +1482,8 @@ default_imp_for_frm_fulfillment!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1372,10 +1516,14 @@ default_imp_for_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1384,7 +1532,8 @@ default_imp_for_frm_record_return!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_revoking_mandates {
@@ -1414,10 +1563,14 @@ default_imp_for_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1426,5 +1579,6 @@ default_imp_for_revoking_mandates!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 54c0b6a8289..5b0edb55ef1 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -217,10 +217,14 @@ default_imp_for_new_connector_integration_payment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -229,7 +233,8 @@ default_imp_for_new_connector_integration_payment!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_refund {
@@ -261,10 +266,14 @@ default_imp_for_new_connector_integration_refund!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -273,7 +282,8 @@ default_imp_for_new_connector_integration_refund!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_connector_access_token {
@@ -300,10 +310,14 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -312,7 +326,8 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_accept_dispute {
@@ -345,10 +360,14 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -357,7 +376,8 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_submit_evidence {
@@ -389,10 +409,14 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -401,7 +425,8 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_defend_dispute {
@@ -433,10 +458,14 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -445,7 +474,8 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_file_upload {
@@ -487,10 +517,14 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -499,7 +533,8 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -533,10 +568,14 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -545,7 +584,8 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -579,10 +619,14 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -591,7 +635,8 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -625,10 +670,14 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -637,7 +686,8 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -671,10 +721,14 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -683,7 +737,8 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -717,10 +772,14 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -729,7 +788,8 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -763,10 +823,14 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -775,7 +839,8 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -809,10 +874,14 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -821,7 +890,8 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "payouts")]
@@ -855,10 +925,14 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -867,7 +941,8 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_webhook_source_verification {
@@ -899,10 +974,14 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -911,7 +990,8 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -945,10 +1025,14 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -957,7 +1041,8 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -991,10 +1076,14 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1003,7 +1092,8 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1037,10 +1127,14 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1049,7 +1143,8 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1083,10 +1178,14 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1095,7 +1194,8 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
#[cfg(feature = "frm")]
@@ -1129,10 +1229,14 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1141,7 +1245,8 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
@@ -1172,10 +1277,14 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
+ connectors::Forte,
connectors::Globepay,
connectors::Helcim,
connectors::Novalnet,
+ connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Payeezy,
+ connectors::Payu,
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
@@ -1184,5 +1293,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Thunes,
connectors::Tsys,
connectors::Worldline,
- connectors::Volt
+ connectors::Volt,
+ connectors::Zen
);
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 0134253f2f9..652ec82c5ed 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -32,6 +32,8 @@ use once_cell::sync::Lazy;
use regex::Regex;
use serde::Serializer;
+use crate::types::RefreshTokenRouterData;
+
type Error = error_stack::Report<errors::ConnectorError>;
pub(crate) fn construct_not_supported_error_report(
@@ -45,6 +47,15 @@ pub(crate) fn construct_not_supported_error_report(
.into()
}
+pub(crate) fn to_currency_base_unit_with_zero_decimal_check(
+ amount: i64,
+ currency: enums::Currency,
+) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ currency
+ .to_currency_base_unit_with_zero_decimal_check(amount)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+}
+
pub(crate) fn get_amount_as_string(
currency_unit: &api::CurrencyUnit,
amount: i64,
@@ -193,6 +204,16 @@ pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
}
}
+pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
+ match status {
+ common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => {
+ true
+ }
+ common_enums::RefundStatus::ManualReview
+ | common_enums::RefundStatus::Pending
+ | common_enums::RefundStatus::Success => false,
+ }
+}
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -892,6 +913,19 @@ static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy
map
});
+pub trait AccessTokenRequestInfo {
+ fn get_request_id(&self) -> Result<Secret<String>, Error>;
+}
+
+impl AccessTokenRequestInfo for RefreshTokenRouterData {
+ fn get_request_id(&self) -> Result<Secret<String>, Error> {
+ self.request
+ .id
+ .clone()
+ .ok_or_else(missing_field_err("request.id"))
+ }
+}
+
pub trait AddressDetailsData {
fn get_first_name(&self) -> Result<&Secret<String>, Error>;
fn get_last_name(&self) -> Result<&Secret<String>, Error>;
@@ -2051,3 +2085,67 @@ impl From<PaymentMethodData> for PaymentMethodDataType {
}
}
}
+pub trait ApplePay {
+ fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
+}
+
+impl ApplePay for hyperswitch_domain_models::payment_method_data::ApplePayWalletData {
+ fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
+ let token = Secret::new(
+ String::from_utf8(BASE64_ENGINE.decode(&self.payment_data).change_context(
+ errors::ConnectorError::InvalidWalletToken {
+ wallet_name: "Apple Pay".to_string(),
+ },
+ )?)
+ .change_context(errors::ConnectorError::InvalidWalletToken {
+ wallet_name: "Apple Pay".to_string(),
+ })?,
+ );
+ Ok(token)
+ }
+}
+
+pub trait WalletData {
+ fn get_wallet_token(&self) -> Result<Secret<String>, Error>;
+ fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
+ where
+ T: serde::de::DeserializeOwned;
+ fn get_encoded_wallet_token(&self) -> Result<String, Error>;
+}
+
+impl WalletData for hyperswitch_domain_models::payment_method_data::WalletData {
+ fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
+ match self {
+ Self::GooglePay(data) => Ok(Secret::new(data.tokenization_data.token.clone())),
+ Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
+ Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
+ _ => Err(errors::ConnectorError::InvalidWallet.into()),
+ }
+ }
+ fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
+ where
+ T: serde::de::DeserializeOwned,
+ {
+ serde_json::from_str::<T>(self.get_wallet_token()?.peek())
+ .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name })
+ }
+
+ fn get_encoded_wallet_token(&self) -> Result<String, Error> {
+ match self {
+ Self::GooglePay(_) => {
+ let json_token: serde_json::Value =
+ self.get_wallet_token_as_json("Google Pay".to_owned())?;
+ let token_as_vec = serde_json::to_vec(&json_token).change_context(
+ errors::ConnectorError::InvalidWalletToken {
+ wallet_name: "Google Pay".to_string(),
+ },
+ )?;
+ let encoded_token = BASE64_ENGINE.encode(token_as_vec);
+ Ok(encoded_token)
+ }
+ _ => Err(
+ errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(),
+ ),
+ }
+ }
+}
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index c0c64d76415..d8d834e759a 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -14,7 +14,6 @@ pub mod datatrans;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
-pub mod forte;
pub mod globalpay;
pub mod gocardless;
pub mod gpayments;
@@ -24,18 +23,15 @@ pub mod klarna;
pub mod mifinity;
pub mod multisafepay;
pub mod netcetera;
-pub mod nexinets;
pub mod nmi;
pub mod noon;
pub mod nuvei;
pub mod opayo;
pub mod opennode;
pub mod paybox;
-pub mod payeezy;
pub mod payme;
pub mod payone;
pub mod paypal;
-pub mod payu;
pub mod placetopay;
pub mod plaid;
pub mod prophetpay;
@@ -52,7 +48,6 @@ pub mod wellsfargo;
pub mod wellsfargopayout;
pub mod wise;
pub mod worldpay;
-pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
@@ -60,10 +55,12 @@ pub use hyperswitch_connectors::connectors::{
cashtocode::Cashtocode, coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay,
deutschebank, deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal,
dlocal::Dlocal, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu,
- globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
- nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, square,
- square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys,
- tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline,
+ forte, forte::Forte, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie,
+ mollie::Mollie, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, novalnet,
+ novalnet::Novalnet, payeezy, payeezy::Payeezy, payu, payu::Payu, powertranz,
+ powertranz::Powertranz, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar,
+ thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline,
+ zen, zen::Zen,
};
#[cfg(feature = "dummy_connector")]
@@ -72,13 +69,12 @@ pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
- cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, forte::Forte,
- globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
- itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
- netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo,
- opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone,
- paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, prophetpay::Prophetpay,
+ cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, globalpay::Globalpay,
+ gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank,
+ klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, netcetera::Netcetera, nmi::Nmi,
+ noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payme::Payme,
+ payone::Payone, paypal::Paypal, placetopay::Placetopay, plaid::Plaid, prophetpay::Prophetpay,
rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd,
stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargo::Wellsfargo,
- wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, zsl::Zsl,
};
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 4e900321f95..80a06bbc482 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -704,7 +704,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -714,18 +713,15 @@ default_imp_for_new_connector_integration_payment!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -740,7 +736,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -776,7 +771,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -786,18 +780,15 @@ default_imp_for_new_connector_integration_refund!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -811,7 +802,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -842,7 +832,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -852,18 +841,15 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -877,7 +863,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -930,7 +915,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -940,18 +924,15 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -965,7 +946,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1000,7 +980,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1010,18 +989,15 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1035,7 +1011,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1054,7 +1029,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1064,18 +1038,15 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1089,7 +1060,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1135,7 +1105,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1145,18 +1114,15 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1170,7 +1136,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1296,7 +1261,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1306,18 +1270,15 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1331,7 +1292,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1369,7 +1329,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1379,18 +1338,15 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1404,7 +1360,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1442,7 +1397,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1452,18 +1406,15 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1477,7 +1428,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1515,7 +1465,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1525,18 +1474,15 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1550,7 +1496,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1588,7 +1533,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1598,18 +1542,15 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1623,7 +1564,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1661,7 +1601,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1671,18 +1610,15 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1696,7 +1632,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1734,7 +1669,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1744,18 +1678,15 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1769,7 +1700,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1807,7 +1737,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1817,18 +1746,15 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1842,7 +1768,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -1878,7 +1803,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1888,18 +1812,15 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1913,7 +1834,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2039,7 +1959,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2049,18 +1968,15 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2074,7 +1990,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2112,7 +2027,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2122,18 +2036,15 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2147,7 +2058,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2185,7 +2095,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2195,18 +2104,15 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2220,7 +2126,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2258,7 +2163,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2268,18 +2172,15 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2293,7 +2194,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2331,7 +2231,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2341,18 +2240,15 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2366,7 +2262,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
@@ -2401,7 +2296,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2411,18 +2305,15 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -2436,7 +2327,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Wellsfargo,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Plaid
);
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 700fff16cf5..3078cf72256 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -212,7 +212,6 @@ default_imp_for_complete_authorize!(
connector::Checkout,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -221,13 +220,10 @@ default_imp_for_complete_authorize!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Noon,
connector::Opayo,
connector::Opennode,
- connector::Payeezy,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Rapyd,
@@ -240,7 +236,6 @@ default_imp_for_complete_authorize!(
connector::Wise,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Zen,
connector::Zsl
);
macro_rules! default_imp_for_webhook_source_verification {
@@ -284,7 +279,6 @@ default_imp_for_webhook_source_verification!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -294,17 +288,14 @@ default_imp_for_webhook_source_verification!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -320,7 +311,6 @@ default_imp_for_webhook_source_verification!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -366,7 +356,6 @@ default_imp_for_create_customer!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -375,18 +364,15 @@ default_imp_for_create_customer!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -401,7 +387,6 @@ default_imp_for_create_customer!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -444,7 +429,6 @@ default_imp_for_connector_redirect_response!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -453,12 +437,9 @@ default_imp_for_connector_redirect_response!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Opayo,
connector::Opennode,
- connector::Payeezy,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -606,7 +587,6 @@ default_imp_for_accept_dispute!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -616,18 +596,15 @@ default_imp_for_accept_dispute!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -643,7 +620,6 @@ default_imp_for_accept_dispute!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -709,7 +685,6 @@ default_imp_for_file_upload!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -719,17 +694,14 @@ default_imp_for_file_upload!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -745,7 +717,6 @@ default_imp_for_file_upload!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -789,7 +760,6 @@ default_imp_for_submit_evidence!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -799,17 +769,14 @@ default_imp_for_submit_evidence!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -825,7 +792,6 @@ default_imp_for_submit_evidence!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -870,7 +836,6 @@ default_imp_for_defend_dispute!(
connector::Datatrans,
connector::Ebanx,
connector::Globalpay,
- connector::Forte,
connector::Gocardless,
connector::Gpayments,
connector::Iatapay,
@@ -879,17 +844,14 @@ default_imp_for_defend_dispute!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -906,7 +868,6 @@ default_imp_for_defend_dispute!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -966,21 +927,17 @@ default_imp_for_pre_processing_steps!(
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
- connector::Forte,
connector::Globalpay,
connector::Gpayments,
connector::Klarna,
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -993,7 +950,6 @@ default_imp_for_pre_processing_steps!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1034,21 +990,17 @@ default_imp_for_post_processing_steps!(
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
- connector::Forte,
connector::Globalpay,
connector::Gpayments,
connector::Klarna,
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Prophetpay,
connector::Rapyd,
@@ -1059,7 +1011,6 @@ default_imp_for_post_processing_steps!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl,
connector::Razorpay
);
@@ -1188,7 +1139,6 @@ default_imp_for_payouts_create!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1198,17 +1148,14 @@ default_imp_for_payouts_create!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1222,7 +1169,6 @@ default_imp_for_payouts_create!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1269,7 +1215,6 @@ default_imp_for_payouts_retrieve!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1279,17 +1224,14 @@ default_imp_for_payouts_retrieve!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1305,7 +1247,6 @@ default_imp_for_payouts_retrieve!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1353,7 +1294,6 @@ default_imp_for_payouts_eligibility!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1363,18 +1303,15 @@ default_imp_for_payouts_eligibility!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1389,7 +1326,6 @@ default_imp_for_payouts_eligibility!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1432,7 +1368,6 @@ default_imp_for_payouts_fulfill!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1442,16 +1377,13 @@ default_imp_for_payouts_fulfill!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1465,7 +1397,6 @@ default_imp_for_payouts_fulfill!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1510,7 +1441,6 @@ default_imp_for_payouts_cancel!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1520,18 +1450,15 @@ default_imp_for_payouts_cancel!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1545,7 +1472,6 @@ default_imp_for_payouts_cancel!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1591,7 +1517,6 @@ default_imp_for_payouts_quote!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1601,18 +1526,15 @@ default_imp_for_payouts_quote!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1627,7 +1549,6 @@ default_imp_for_payouts_quote!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1673,7 +1594,6 @@ default_imp_for_payouts_recipient!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1683,18 +1603,15 @@ default_imp_for_payouts_recipient!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1708,7 +1625,6 @@ default_imp_for_payouts_recipient!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1758,7 +1674,6 @@ default_imp_for_payouts_recipient_account!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1768,18 +1683,15 @@ default_imp_for_payouts_recipient_account!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1794,7 +1706,6 @@ default_imp_for_payouts_recipient_account!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1840,7 +1751,6 @@ default_imp_for_approve!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1850,18 +1760,15 @@ default_imp_for_approve!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1877,7 +1784,6 @@ default_imp_for_approve!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -1923,7 +1829,6 @@ default_imp_for_reject!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -1933,18 +1838,15 @@ default_imp_for_reject!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -1960,7 +1862,6 @@ default_imp_for_reject!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2097,7 +1998,6 @@ default_imp_for_frm_sale!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2107,18 +2007,15 @@ default_imp_for_frm_sale!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2132,7 +2029,6 @@ default_imp_for_frm_sale!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2180,7 +2076,6 @@ default_imp_for_frm_checkout!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2190,18 +2085,15 @@ default_imp_for_frm_checkout!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2215,7 +2107,6 @@ default_imp_for_frm_checkout!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2263,7 +2154,6 @@ default_imp_for_frm_transaction!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2273,18 +2163,15 @@ default_imp_for_frm_transaction!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2298,7 +2185,6 @@ default_imp_for_frm_transaction!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2346,7 +2232,6 @@ default_imp_for_frm_fulfillment!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2356,18 +2241,15 @@ default_imp_for_frm_fulfillment!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2381,7 +2263,6 @@ default_imp_for_frm_fulfillment!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2429,7 +2310,6 @@ default_imp_for_frm_record_return!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2439,18 +2319,15 @@ default_imp_for_frm_record_return!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2464,7 +2341,6 @@ default_imp_for_frm_record_return!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2509,7 +2385,6 @@ default_imp_for_incremental_authorization!(
connector::Checkout,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2519,18 +2394,15 @@ default_imp_for_incremental_authorization!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2545,7 +2417,6 @@ default_imp_for_incremental_authorization!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2588,7 +2459,6 @@ default_imp_for_revoking_mandates!(
connector::Checkout,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2598,17 +2468,14 @@ default_imp_for_revoking_mandates!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2622,7 +2489,6 @@ default_imp_for_revoking_mandates!(
connector::Trustpay,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2828,7 +2694,6 @@ default_imp_for_authorize_session_token!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2838,17 +2703,14 @@ default_imp_for_authorize_session_token!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nmi,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2864,7 +2726,6 @@ default_imp_for_authorize_session_token!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2908,7 +2769,6 @@ default_imp_for_calculate_tax!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2918,18 +2778,15 @@ default_imp_for_calculate_tax!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nuvei,
connector::Nmi,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
connector::Paypal,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -2945,7 +2802,6 @@ default_imp_for_calculate_tax!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -2989,7 +2845,6 @@ default_imp_for_session_update!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -2999,17 +2854,14 @@ default_imp_for_session_update!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nuvei,
connector::Nmi,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -3025,7 +2877,6 @@ default_imp_for_session_update!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
@@ -3069,7 +2920,6 @@ default_imp_for_post_session_tokens!(
connector::Cybersource,
connector::Datatrans,
connector::Ebanx,
- connector::Forte,
connector::Globalpay,
connector::Gocardless,
connector::Gpayments,
@@ -3079,17 +2929,14 @@ default_imp_for_post_session_tokens!(
connector::Mifinity,
connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
connector::Nuvei,
connector::Nmi,
connector::Noon,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
connector::Payone,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
connector::Prophetpay,
@@ -3105,6 +2952,5 @@ default_imp_for_post_session_tokens!(
connector::Wellsfargopayout,
connector::Wise,
connector::Worldpay,
- connector::Zen,
connector::Zsl
);
| 2024-10-08T08:03:24Z |
## Description
<!-- Describe your changes in detail -->
Moved connectors Forte, Nexinets, Payeezy, Payu and Zen from Router to HyperswitchConnector Trait
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
Forte :
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {}' \
--data-raw '{
"merchant_id": "merchant_1728385434",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://duck.com",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
],
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728384837' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ••••••' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728384837/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "forte",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "MultiAuthKey",
"api_key": "0ec**********",
"api_secret": "38ee*************",
"key1": "4******",
"key2": "31******"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using forte
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_dEtbKypkYuZjjaJ9pXTN2SRHRlqYZvqHlr2EXaj3x44lU7RnCZQTSFKGaeDJ895B' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_79ecqpcbnM7HUPpwoOFD",
"merchant_id": "merchant_1728384837",
"status": "processing",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "forte",
"client_secret": "pay_79ecqpcbnM7HUPpwoOFD_secret_UJ0TMFRIrpHXPpXwu2hT",
"created": "2024-10-08T10:54:06.768Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1728384846,
"expires": 1728388446,
"secret": "epk_12e5c9695a754adabd3dcbd41538ae9a"
},
"manual_retry_allowed": false,
"connector_transaction_id": "trn_8daaa862-1941-4d53-aadd-6297fcf0a6e3",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "trn_8daaa862-1941-4d53-aadd-6297fcf0a6e3",
"payment_link": null,
"profile_id": "pro_4eQhw3L62I6ysvxyPOic",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_M8CQa7cLpd2ymAIHj63T",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T11:09:06.768Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T10:54:08.404Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Retreive Payments
```
curl --location 'http://localhost:8080/payments/pay_79ecqpcbnM7HUPpwoOFD?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_dEtbKypkYuZjjaJ9pXTN2SRHRlqYZvqHlr2EXaj3x44lU7RnCZQTSFKGaeDJ895B'
```
---
Nexinets:
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{"merchant_id":"merchant_1728991500","locker_id":"m0010","merchant_name":"NewAge Retailer","merchant_details":{"primary_contact_person":"John Test","primary_email":"JohnTest@test.com","primary_phone":"sunt laborum","secondary_contact_person":"John Test2","secondary_email":"JohnTest2@test.com","secondary_phone":"cillum do dolor id","website":"www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US"}},"return_url":"https://duck.com","webhook_details":{"webhook_version":"1.0.1","webhook_username":"ekart_retail","webhook_password":"password_ekart@123","payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true},"primary_business_details":[{"country":"US","business":"default"}],"sub_merchants_enabled":false,"metadata":{"city":"NY","unit":"245"}}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728991473' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728991473/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "nexinets",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "mNm__",
"key1": "me___"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using Nexinets
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_lHnj44I4xXpfypavL5Ppi2cAEdtdw9CTE6FsbmJlUa73pL6qfBYGXrvY6pGfbcsn' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"payment_id": "pay_ImQuAxz1Y2uiVIgoQBlW",
"merchant_id": "merchant_1728991473",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "nexinets",
"client_secret": "pay_ImQuAxz1Y2uiVIgoQBlW_secret_SEofo0xTzEvC1H2nELXi",
"created": "2024-10-15T11:24:43.098Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "JP Morgan",
"card_issuing_country": "INDIA",
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_ImQuAxz1Y2uiVIgoQBlW/merchant_1728991473/pay_ImQuAxz1Y2uiVIgoQBlW_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1728991483,
"expires": 1728995083,
"secret": "epk_bad59c12bb8e435b871f4883793eae85"
},
"manual_retry_allowed": null,
"connector_transaction_id": "transaction_ii85qwfojj",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "un68m4lvbd",
"payment_link": null,
"profile_id": "pro_vj31P4oHhu1UsKG3jKxf",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_PFJ53QJ9BhhL4VipytnI",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-15T11:39:43.098Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-15T11:24:44.113Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Payment Retrieve
Request:
```
curl --location 'http://localhost:8080/payments/pay_XXCjWlYtKMe4XMLUfACD' \
--header 'Accept: application/json' \
--header 'api-key: dev_lHnj44I4xXpfypavL5Ppi2cAEdtdw9CTE6FsbmJlUa73pL6qfBYGXrvY6pGfbcsn'
```
Response
```
{
"payment_id": "pay_1QUgZraA5RE7vowPPReV",
"merchant_id": "merchant_1728991673",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "nexinets",
"client_secret": "pay_1QUgZraA5RE7vowPPReV_secret_5NCsu0miNqGXqWUHHYp9",
"created": "2024-10-15T11:28:09.327Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "JP Morgan",
"card_issuing_country": "INDIA",
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_1QUgZraA5RE7vowPPReV/merchant_1728991673/pay_1QUgZraA5RE7vowPPReV_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "transaction_n7yev7ilqb",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "doryyd1r1i",
"payment_link": null,
"profile_id": "pro_66SswnUJqssaC64fPLiO",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_a1skdhzvPLfj9vlQu3AE",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-15T11:43:09.327Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-15T11:28:11.345Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
---
Payu:
1. Create Merchant Account:
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1729149396",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://duck.com",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
],
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729149277' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1729149277/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "payu",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "0d6___",
"key1": "4____14"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using Payu
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Dwn1IhykL7JFo5KDF9obKKLGZB6D6mStkxb0CT3Y3zDiaNvPP4o7eXCwJlBv7Yic' \
--data-raw '{
"amount": 6540,
"currency": "PLN",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_SOFkngQbJEUOYmCPwuYk",
"merchant_id": "merchant_1729074298",
"status": "processing",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "payu",
"client_secret": "pay_SOFkngQbJEUOYmCPwuYk_secret_PSdwKWhCaqZ6VYk8ibla",
"created": "2024-10-16T10:39:06.648Z",
"currency": "PLN",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1729075146,
"expires": 1729078746,
"secret": "epk_73a0536f49dc4ab2ba15aa7d30ce0720"
},
"manual_retry_allowed": false,
"connector_transaction_id": "9DZ4CT4F76241016GUEST000P01",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "9DZ4CT4F76241016GUEST000P01",
"payment_link": null,
"profile_id": "pro_zi8dc3x41XN625phjqDZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nDAA7DczPrC2UfIOToLP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-16T10:54:06.648Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-16T10:39:08.346Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Payment Retrieve
```
curl --location 'http://localhost:8080/payments/pay_SOFkngQbJEUOYmCPwuYk' \
--header 'Accept: application/json' \
--header 'api-key: dev_Dwn1IhykL7JFo5KDF9obKKLGZB6D6mStkxb0CT3Y3zDiaNvPP4o7eXCwJlBv7Yic'
```
---
Payeezy and Zen not tested due to some issue with credentials | f3a869ea9a430f3b5177852fb74d0910dc8fbe17 | Forte :
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {}' \
--data-raw '{
"merchant_id": "merchant_1728385434",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://duck.com",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
],
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728384837' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ••••••' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728384837/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "forte",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "MultiAuthKey",
"api_key": "0ec**********",
"api_secret": "38ee*************",
"key1": "4******",
"key2": "31******"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using forte
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_dEtbKypkYuZjjaJ9pXTN2SRHRlqYZvqHlr2EXaj3x44lU7RnCZQTSFKGaeDJ895B' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_79ecqpcbnM7HUPpwoOFD",
"merchant_id": "merchant_1728384837",
"status": "processing",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "forte",
"client_secret": "pay_79ecqpcbnM7HUPpwoOFD_secret_UJ0TMFRIrpHXPpXwu2hT",
"created": "2024-10-08T10:54:06.768Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1728384846,
"expires": 1728388446,
"secret": "epk_12e5c9695a754adabd3dcbd41538ae9a"
},
"manual_retry_allowed": false,
"connector_transaction_id": "trn_8daaa862-1941-4d53-aadd-6297fcf0a6e3",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "trn_8daaa862-1941-4d53-aadd-6297fcf0a6e3",
"payment_link": null,
"profile_id": "pro_4eQhw3L62I6ysvxyPOic",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_M8CQa7cLpd2ymAIHj63T",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T11:09:06.768Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T10:54:08.404Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Retreive Payments
```
curl --location 'http://localhost:8080/payments/pay_79ecqpcbnM7HUPpwoOFD?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_dEtbKypkYuZjjaJ9pXTN2SRHRlqYZvqHlr2EXaj3x44lU7RnCZQTSFKGaeDJ895B'
```
---
Nexinets:
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{"merchant_id":"merchant_1728991500","locker_id":"m0010","merchant_name":"NewAge Retailer","merchant_details":{"primary_contact_person":"John Test","primary_email":"JohnTest@test.com","primary_phone":"sunt laborum","secondary_contact_person":"John Test2","secondary_email":"JohnTest2@test.com","secondary_phone":"cillum do dolor id","website":"www.example.com","about_business":"Online Retail with a wide selection of organic products for North America","address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US"}},"return_url":"https://duck.com","webhook_details":{"webhook_version":"1.0.1","webhook_username":"ekart_retail","webhook_password":"password_ekart@123","payment_created_enabled":true,"payment_succeeded_enabled":true,"payment_failed_enabled":true},"primary_business_details":[{"country":"US","business":"default"}],"sub_merchants_enabled":false,"metadata":{"city":"NY","unit":"245"}}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1728991473' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1728991473/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "nexinets",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "mNm__",
"key1": "me___"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using Nexinets
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_lHnj44I4xXpfypavL5Ppi2cAEdtdw9CTE6FsbmJlUa73pL6qfBYGXrvY6pGfbcsn' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"payment_id": "pay_ImQuAxz1Y2uiVIgoQBlW",
"merchant_id": "merchant_1728991473",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "nexinets",
"client_secret": "pay_ImQuAxz1Y2uiVIgoQBlW_secret_SEofo0xTzEvC1H2nELXi",
"created": "2024-10-15T11:24:43.098Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "JP Morgan",
"card_issuing_country": "INDIA",
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_ImQuAxz1Y2uiVIgoQBlW/merchant_1728991473/pay_ImQuAxz1Y2uiVIgoQBlW_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1728991483,
"expires": 1728995083,
"secret": "epk_bad59c12bb8e435b871f4883793eae85"
},
"manual_retry_allowed": null,
"connector_transaction_id": "transaction_ii85qwfojj",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "un68m4lvbd",
"payment_link": null,
"profile_id": "pro_vj31P4oHhu1UsKG3jKxf",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_PFJ53QJ9BhhL4VipytnI",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-15T11:39:43.098Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-15T11:24:44.113Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Payment Retrieve
Request:
```
curl --location 'http://localhost:8080/payments/pay_XXCjWlYtKMe4XMLUfACD' \
--header 'Accept: application/json' \
--header 'api-key: dev_lHnj44I4xXpfypavL5Ppi2cAEdtdw9CTE6FsbmJlUa73pL6qfBYGXrvY6pGfbcsn'
```
Response
```
{
"payment_id": "pay_1QUgZraA5RE7vowPPReV",
"merchant_id": "merchant_1728991673",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "nexinets",
"client_secret": "pay_1QUgZraA5RE7vowPPReV_secret_5NCsu0miNqGXqWUHHYp9",
"created": "2024-10-15T11:28:09.327Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "JP Morgan",
"card_issuing_country": "INDIA",
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_1QUgZraA5RE7vowPPReV/merchant_1728991673/pay_1QUgZraA5RE7vowPPReV_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "transaction_n7yev7ilqb",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "doryyd1r1i",
"payment_link": null,
"profile_id": "pro_66SswnUJqssaC64fPLiO",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_a1skdhzvPLfj9vlQu3AE",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-15T11:43:09.327Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-15T11:28:11.345Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
---
Payu:
1. Create Merchant Account:
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1729149396",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://duck.com",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
],
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729149277' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{"name":"API Key 1","description":null,"expiration":"2069-09-23T01:02:03.000Z"}'
```
3. Create Payment Connector
```
curl --location 'http://localhost:8080/account/merchant_1729149277/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "payu",
"business_country": "US",
"business_label": "default",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "0d6___",
"key1": "4____14"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"gpay": {
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "example",
"gateway_merchant_id": "exampleGatewayMerchantId"
}
}
}
],
"merchant_info": {
"merchant_name": "Narayan Bhat"
}
}
}
}'
```
4. Create Payments using Payu
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Dwn1IhykL7JFo5KDF9obKKLGZB6D6mStkxb0CT3Y3zDiaNvPP4o7eXCwJlBv7Yic' \
--data-raw '{
"amount": 6540,
"currency": "PLN",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "Fix"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
```
Response:
```
{
"payment_id": "pay_SOFkngQbJEUOYmCPwuYk",
"merchant_id": "merchant_1729074298",
"status": "processing",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "payu",
"client_secret": "pay_SOFkngQbJEUOYmCPwuYk_secret_PSdwKWhCaqZ6VYk8ibla",
"created": "2024-10-16T10:39:06.648Z",
"currency": "PLN",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "Fix"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1729075146,
"expires": 1729078746,
"secret": "epk_73a0536f49dc4ab2ba15aa7d30ce0720"
},
"manual_retry_allowed": false,
"connector_transaction_id": "9DZ4CT4F76241016GUEST000P01",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "9DZ4CT4F76241016GUEST000P01",
"payment_link": null,
"profile_id": "pro_zi8dc3x41XN625phjqDZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nDAA7DczPrC2UfIOToLP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-16T10:54:06.648Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-16T10:39:08.346Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
5. Payment Retrieve
```
curl --location 'http://localhost:8080/payments/pay_SOFkngQbJEUOYmCPwuYk' \
--header 'Accept: application/json' \
--header 'api-key: dev_Dwn1IhykL7JFo5KDF9obKKLGZB6D6mStkxb0CT3Y3zDiaNvPP4o7eXCwJlBv7Yic'
```
---
Payeezy and Zen not tested due to some issue with credentials
| [
"Cargo.lock",
"crates/common_utils/src/consts.rs",
"crates/hyperswitch_connectors/Cargo.toml",
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/forte.rs",
"crates/router/src/connector/forte/transformers.rs",
"crates/router/src/connector/nexinets.rs",
"crates/router/src/c... | |
juspay/hyperswitch | juspay__hyperswitch-6258 | Bug: Add support for Samsung pay app token flow
Samsung pay provide token in different format for web and app. Hence both of the formates needs to be handled in confirm call. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 44ac1d3e08d..13d0cc87ccf 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -18929,6 +18929,61 @@
"FORMAT_TOTAL_ESTIMATED_AMOUNT"
]
},
+ "SamsungPayAppWalletData": {
+ "type": "object",
+ "required": [
+ "3_d_s",
+ "payment_card_brand",
+ "payment_currency_type",
+ "payment_last4_fpan"
+ ],
+ "properties": {
+ "3_d_s": {
+ "$ref": "#/components/schemas/SamsungPayTokenData"
+ },
+ "payment_card_brand": {
+ "$ref": "#/components/schemas/SamsungPayCardBrand"
+ },
+ "payment_currency_type": {
+ "type": "string",
+ "description": "Currency type of the payment"
+ },
+ "payment_last4_dpan": {
+ "type": "string",
+ "description": "Last 4 digits of the device specific card number",
+ "nullable": true
+ },
+ "payment_last4_fpan": {
+ "type": "string",
+ "description": "Last 4 digits of the card number"
+ },
+ "merchant_ref": {
+ "type": "string",
+ "description": "Merchant reference id that was passed in the session call request",
+ "nullable": true
+ },
+ "method": {
+ "type": "string",
+ "description": "Specifies authentication method used",
+ "nullable": true
+ },
+ "recurring_payment": {
+ "type": "boolean",
+ "description": "Value if credential is enabled for recurring payment",
+ "nullable": true
+ }
+ }
+ },
+ "SamsungPayCardBrand": {
+ "type": "string",
+ "enum": [
+ "visa",
+ "mastercard",
+ "amex",
+ "discover",
+ "unknown"
+ ]
+ },
"SamsungPayMerchantPaymentInformation": {
"type": "object",
"required": [
@@ -19021,6 +19076,27 @@
}
},
"SamsungPayWalletCredentials": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/SamsungPayWebWalletData"
+ },
+ {
+ "$ref": "#/components/schemas/SamsungPayAppWalletData"
+ }
+ ]
+ },
+ "SamsungPayWalletData": {
+ "type": "object",
+ "required": [
+ "payment_credential"
+ ],
+ "properties": {
+ "payment_credential": {
+ "$ref": "#/components/schemas/SamsungPayWalletCredentials"
+ }
+ }
+ },
+ "SamsungPayWebWalletData": {
"type": "object",
"required": [
"card_brand",
@@ -19039,8 +19115,7 @@
"nullable": true
},
"card_brand": {
- "type": "string",
- "description": "Brand of the payment card"
+ "$ref": "#/components/schemas/SamsungPayCardBrand"
},
"card_last4digits": {
"type": "string",
@@ -19051,17 +19126,6 @@
}
}
},
- "SamsungPayWalletData": {
- "type": "object",
- "required": [
- "payment_credential"
- ],
- "properties": {
- "payment_credential": {
- "$ref": "#/components/schemas/SamsungPayWalletCredentials"
- }
- }
- },
"SdkInformation": {
"type": "object",
"description": "SDK Information if request is from SDK",
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a758d457858..0acbdd50a89 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2908,15 +2908,56 @@ pub struct SamsungPayWalletData {
pub payment_credential: SamsungPayWalletCredentials,
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case", untagged)]
+pub enum SamsungPayWalletCredentials {
+ SamsungPayWalletDataForWeb(SamsungPayWebWalletData),
+ SamsungPayWalletDataForApp(SamsungPayAppWalletData),
+}
+
+impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand {
+ fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self {
+ match samsung_pay_card_brand {
+ SamsungPayCardBrand::Visa => Self::Visa,
+ SamsungPayCardBrand::MasterCard => Self::MasterCard,
+ SamsungPayCardBrand::Amex => Self::Amex,
+ SamsungPayCardBrand::Discover => Self::Discover,
+ SamsungPayCardBrand::Unknown => Self::Unknown,
+ }
+ }
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct SamsungPayAppWalletData {
+ /// Samsung Pay token data
+ #[serde(rename = "3_d_s")]
+ pub token_data: SamsungPayTokenData,
+ /// Brand of the payment card
+ pub payment_card_brand: SamsungPayCardBrand,
+ /// Currency type of the payment
+ pub payment_currency_type: String,
+ /// Last 4 digits of the device specific card number
+ pub payment_last4_dpan: Option<String>,
+ /// Last 4 digits of the card number
+ pub payment_last4_fpan: String,
+ /// Merchant reference id that was passed in the session call request
+ pub merchant_ref: Option<String>,
+ /// Specifies authentication method used
+ pub method: Option<String>,
+ /// Value if credential is enabled for recurring payment
+ pub recurring_payment: Option<bool>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
-pub struct SamsungPayWalletCredentials {
+pub struct SamsungPayWebWalletData {
/// Specifies authentication method used
pub method: Option<String>,
/// Value if credential is enabled for recurring payment
pub recurring_payment: Option<bool>,
/// Brand of the payment card
- pub card_brand: String,
+ pub card_brand: SamsungPayCardBrand,
/// Last 4 digits of the card number
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
@@ -2938,6 +2979,21 @@ pub struct SamsungPayTokenData {
pub data: Secret<String>,
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum SamsungPayCardBrand {
+ #[serde(alias = "VI")]
+ Visa,
+ #[serde(alias = "MC")]
+ MasterCard,
+ #[serde(alias = "AX")]
+ Amex,
+ #[serde(alias = "DC")]
+ Discover,
+ #[serde(other)]
+ Unknown,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum OpenBankingData {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 5ab05c9a688..4601a818fb3 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1509,6 +1509,16 @@ pub enum PaymentExperience {
DisplayWaitScreen,
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display)]
+#[serde(rename_all = "lowercase")]
+pub enum SamsungPayCardBrand {
+ Visa,
+ MasterCard,
+ Amex,
+ Discover,
+ Unknown,
+}
+
/// Indicates the sub type of payment method. Eg: 'google_pay' & 'apple_pay' for wallets.
#[derive(
Clone,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 3ccfabf021c..165e9fdd1c7 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -152,7 +152,8 @@ pub struct SamsungPayWalletData {
pub struct SamsungPayWalletCredentials {
pub method: Option<String>,
pub recurring_payment: Option<bool>,
- pub card_brand: String,
+ pub card_brand: common_enums::SamsungPayCardBrand,
+ pub dpan_last_four_digits: Option<String>,
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
#[serde(rename = "3_d_s")]
@@ -764,6 +765,16 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
}
}
+impl From<api_models::payments::SamsungPayTokenData> for SamsungPayTokenData {
+ fn from(samsung_pay_token_data: api_models::payments::SamsungPayTokenData) -> Self {
+ Self {
+ three_ds_type: samsung_pay_token_data.three_ds_type,
+ version: samsung_pay_token_data.version,
+ data: samsung_pay_token_data.data,
+ }
+ }
+}
+
impl From<api_models::payments::PazeWalletData> for PazeWalletData {
fn from(value: api_models::payments::PazeWalletData) -> Self {
Self {
@@ -774,16 +785,29 @@ impl From<api_models::payments::PazeWalletData> for PazeWalletData {
impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData {
fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self {
- Self {
- payment_credential: SamsungPayWalletCredentials {
- method: value.payment_credential.method,
- recurring_payment: value.payment_credential.recurring_payment,
- card_brand: value.payment_credential.card_brand,
- card_last_four_digits: value.payment_credential.card_last_four_digits,
- token_data: SamsungPayTokenData {
- three_ds_type: value.payment_credential.token_data.three_ds_type,
- version: value.payment_credential.token_data.version,
- data: value.payment_credential.token_data.data,
+ match value.payment_credential {
+ api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForApp(
+ samsung_pay_app_wallet_data,
+ ) => Self {
+ payment_credential: SamsungPayWalletCredentials {
+ method: samsung_pay_app_wallet_data.method,
+ recurring_payment: samsung_pay_app_wallet_data.recurring_payment,
+ card_brand: samsung_pay_app_wallet_data.payment_card_brand.into(),
+ dpan_last_four_digits: samsung_pay_app_wallet_data.payment_last4_dpan,
+ card_last_four_digits: samsung_pay_app_wallet_data.payment_last4_fpan,
+ token_data: samsung_pay_app_wallet_data.token_data.into(),
+ },
+ },
+ api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForWeb(
+ samsung_pay_web_wallet_data,
+ ) => Self {
+ payment_credential: SamsungPayWalletCredentials {
+ method: samsung_pay_web_wallet_data.method,
+ recurring_payment: samsung_pay_web_wallet_data.recurring_payment,
+ card_brand: samsung_pay_web_wallet_data.card_brand.into(),
+ dpan_last_four_digits: None,
+ card_last_four_digits: samsung_pay_web_wallet_data.card_last_four_digits,
+ token_data: samsung_pay_web_wallet_data.token_data.into(),
},
},
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 24fbadc0a59..a818e393f26 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -424,6 +424,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::SamsungPayWalletCredentials,
+ api_models::payments::SamsungPayWebWalletData,
+ api_models::payments::SamsungPayAppWalletData,
+ api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index bc44068030b..dbd19e39212 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -366,6 +366,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::SamsungPayWalletCredentials,
+ api_models::payments::SamsungPayWebWalletData,
+ api_models::payments::SamsungPayAppWalletData,
+ api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 8a6c3c075ff..d3eb6544157 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1666,7 +1666,7 @@ impl
let processing_information = ProcessingInformation::try_from((
item,
Some(PaymentSolution::SamsungPay),
- Some(samsung_pay_data.payment_credential.card_brand),
+ Some(samsung_pay_data.payment_credential.card_brand.to_string()),
))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information = item
| 2024-10-08T04:15:32Z |
## Description
<!-- Describe your changes in detail -->
Samsung pay provide token in different format for web and app. Hence both of the formates needs to be handled in confirm call.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create merchant connector account with samsung pay enabled
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1727978246"
}'
```
```
{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"merchant_id": "merchant_1728361524",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF",
"created": "2024-10-08T04:25:38.101Z",
"currency": "USD",
"customer_id": "cu_1727978246",
"customer": {
"id": "cu_1727978246",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727978246",
"created_at": 1728361538,
"expires": 1728365138,
"secret": "epk_0654d9d63e3f4b8587a3a5d6c00973cb"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:40:38.101Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:25:38.146Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Sessions call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_486c819214dc4b96a6b09c73bc784c99' \
--data '{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"wallets": [],
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF"
}'
```
```
{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_Zl8NvZrYRBm9cAwOJrJE",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Confirm call with samsung pay app token format
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "cu_1727978246",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"payment_card_brand": "VI",
"payment_currency_type": "USD",
"payment_last4_dpan": "****",
"payment_last4_fpan": "****",
"merchant_ref": "123456",
"method": "3DS",
"recurring_payment": false,
"3_d_s": {
"type": "S",
"version": "100",
"data": ""
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_FWyeZ5cJuUOhNT2kbtMl",
"merchant_id": "merchant_1728361524",
"status": "processing",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_FWyeZ5cJuUOhNT2kbtMl_secret_ADiw54HEfb3oJPBpwFkG",
"created": "2024-10-08T04:28:56.781Z",
"currency": "USD",
"customer_id": "cu_1727978246",
"customer": {
"id": "cu_1727978246",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727978246",
"created_at": 1728361736,
"expires": 1728365336,
"secret": "epk_a770a46dcbab4ca6be412ed08cad53d1"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7283617370316400703954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "7283617370316400703954",
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nHYXJ9CkuPebtCA98Hjo",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:43:56.781Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:28:57.546Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Confirm call with samsung pay web token format
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "****",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": ""
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_k83FAY7jSP8kaH9kbNZR",
"merchant_id": "merchant_1728361524",
"status": "processing",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_k83FAY7jSP8kaH9kbNZR_secret_oMJTGbW4JsErHi0k3xrD",
"created": "2024-10-08T04:30:55.281Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1728361855,
"expires": 1728365455,
"secret": "epk_7fabe834ddc043f6a636672918db7230"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7283618563836006703955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "7283618563836006703955",
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nHYXJ9CkuPebtCA98Hjo",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:45:55.281Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:30:56.767Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | edd099886da9c46800a646fe809796a08eb78c99 |
-> Create merchant connector account with samsung pay enabled
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1727978246"
}'
```
```
{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"merchant_id": "merchant_1728361524",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF",
"created": "2024-10-08T04:25:38.101Z",
"currency": "USD",
"customer_id": "cu_1727978246",
"customer": {
"id": "cu_1727978246",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727978246",
"created_at": 1728361538,
"expires": 1728365138,
"secret": "epk_0654d9d63e3f4b8587a3a5d6c00973cb"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:40:38.101Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:25:38.146Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Sessions call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_486c819214dc4b96a6b09c73bc784c99' \
--data '{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"wallets": [],
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF"
}'
```
```
{
"payment_id": "pay_Zl8NvZrYRBm9cAwOJrJE",
"client_secret": "pay_Zl8NvZrYRBm9cAwOJrJE_secret_R0cSTWF8DWj2yDhqdGKF",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_Zl8NvZrYRBm9cAwOJrJE",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Confirm call with samsung pay app token format
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "cu_1727978246",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"payment_card_brand": "VI",
"payment_currency_type": "USD",
"payment_last4_dpan": "****",
"payment_last4_fpan": "****",
"merchant_ref": "123456",
"method": "3DS",
"recurring_payment": false,
"3_d_s": {
"type": "S",
"version": "100",
"data": ""
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_FWyeZ5cJuUOhNT2kbtMl",
"merchant_id": "merchant_1728361524",
"status": "processing",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_FWyeZ5cJuUOhNT2kbtMl_secret_ADiw54HEfb3oJPBpwFkG",
"created": "2024-10-08T04:28:56.781Z",
"currency": "USD",
"customer_id": "cu_1727978246",
"customer": {
"id": "cu_1727978246",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727978246",
"created_at": 1728361736,
"expires": 1728365336,
"secret": "epk_a770a46dcbab4ca6be412ed08cad53d1"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7283617370316400703954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "7283617370316400703954",
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nHYXJ9CkuPebtCA98Hjo",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:43:56.781Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:28:57.546Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Confirm call with samsung pay web token format
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "****",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": ""
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_k83FAY7jSP8kaH9kbNZR",
"merchant_id": "merchant_1728361524",
"status": "processing",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_k83FAY7jSP8kaH9kbNZR_secret_oMJTGbW4JsErHi0k3xrD",
"created": "2024-10-08T04:30:55.281Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1728361855,
"expires": 1728365455,
"secret": "epk_7fabe834ddc043f6a636672918db7230"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7283618563836006703955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "7283618563836006703955",
"payment_link": null,
"profile_id": "pro_O42vzFfJB6dDqb4XUPrZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nHYXJ9CkuPebtCA98Hjo",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-08T04:45:55.281Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-08T04:30:56.767Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/payments.rs",
"crates/common_enums/src/enums.rs",
"crates/hyperswitch_domain_models/src/payment_method_data.rs",
"crates/openapi/src/openapi.rs",
"crates/openapi/src/openapi_v2.rs",
"crates/router/src/connector/cybersource/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6254 | Bug: fix(users): Accepting invite for org_admins
Currently, when email feature flag is enabled and invite a org_admin, it throws error saying `InvalidRoleId`.
When we try to accept invite for `org_admin`s, it again throws `InvalidRoleId`.
This should not be the case, error should not be throws and invite should be accepted. | diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index f4142842e21..5ef09715211 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -119,7 +119,7 @@ impl UserRole {
conn: &PgPooledConn,
user_id: String,
org_id: id_type::OrganizationId,
- merchant_id: id_type::MerchantId,
+ merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
update: UserRoleUpdate,
version: UserRoleVersion,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 91c86a74056..046675f5200 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -647,7 +647,14 @@ async fn handle_existing_user_invitation(
};
let _user_role = match role_info.get_entity_type() {
- EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => {
+ user_role
+ .add_entity(domain::OrganizationLevel {
+ org_id: user_from_token.org_id.clone(),
+ })
+ .insert_in_v2(state)
+ .await?
+ }
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
@@ -678,7 +685,10 @@ async fn handle_existing_user_invitation(
{
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let entity = match role_info.get_entity_type() {
- EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => email_types::Entity {
+ entity_id: user_from_token.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ },
EntityType::Merchant => email_types::Entity {
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
@@ -806,7 +816,10 @@ async fn handle_new_user_invitation(
let _ = req_state.clone();
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let entity = match role_info.get_entity_type() {
- EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => email_types::Entity {
+ entity_id: user_from_token.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ },
EntityType::Merchant => email_types::Entity {
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
@@ -1012,7 +1025,7 @@ pub async fn accept_invite_from_email_token_only_flow(
&state,
user_from_db.get_user_id(),
&org_id,
- &merchant_id,
+ merchant_id.as_ref(),
profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 5973a20dd33..258a88ba9f8 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -166,7 +166,7 @@ pub async fn update_user_role(
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
- &user_from_token.merchant_id,
+ Some(&user_from_token.merchant_id),
user_from_token.profile_id.as_ref(),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
@@ -231,7 +231,7 @@ pub async fn update_user_role(
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
- &user_from_token.merchant_id,
+ Some(&user_from_token.merchant_id),
user_from_token.profile_id.as_ref(),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
@@ -280,7 +280,7 @@ pub async fn accept_invitations_v2(
&state,
user_from_token.user_id.as_str(),
org_id,
- merchant_id,
+ merchant_id.as_ref(),
profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
@@ -332,7 +332,7 @@ pub async fn accept_invitations_pre_auth(
&state,
user_token.user_id.as_str(),
org_id,
- merchant_id,
+ merchant_id.as_ref(),
profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 33f93ecc699..9f237c226b6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3043,7 +3043,7 @@ impl UserRoleInterface for KafkaStore {
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
- merchant_id: &id_type::MerchantId,
+ merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: user_storage::UserRoleUpdate,
version: enums::UserRoleVersion,
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d8ef4881934..b589d375975 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -52,7 +52,7 @@ pub trait UserRoleInterface {
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
- merchant_id: &id_type::MerchantId,
+ merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
@@ -120,7 +120,7 @@ impl UserRoleInterface for Store {
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
- merchant_id: &id_type::MerchantId,
+ merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
@@ -130,7 +130,7 @@ impl UserRoleInterface for Store {
&conn,
user_id.to_owned(),
org_id.to_owned(),
- merchant_id.to_owned(),
+ merchant_id.cloned(),
profile_id.cloned(),
update,
version,
@@ -280,7 +280,7 @@ impl UserRoleInterface for MockDb {
&self,
user_id: &str,
org_id: &id_type::OrganizationId,
- merchant_id: &id_type::MerchantId,
+ merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
@@ -293,11 +293,11 @@ impl UserRoleInterface for MockDb {
&& user_role.profile_id.is_none();
let merchant_level_check = user_role.org_id.as_ref() == Some(org_id)
- && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.merchant_id.as_ref() == merchant_id
&& user_role.profile_id.is_none();
let profile_level_check = user_role.org_id.as_ref() == Some(org_id)
- && user_role.merchant_id.as_ref() == Some(merchant_id)
+ && user_role.merchant_id.as_ref() == merchant_id
&& user_role.profile_id.as_ref() == profile_id;
// Check if the user role matches the conditions and the version matches
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index b6db8340775..0ea423989f5 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -174,7 +174,7 @@ pub async fn update_v1_and_v2_user_roles_in_db(
state: &SessionState,
user_id: &str,
org_id: &id_type::OrganizationId,
- merchant_id: &id_type::MerchantId,
+ merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: UserRoleUpdate,
) -> (
@@ -255,12 +255,57 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
) -> UserResult<
Option<(
id_type::OrganizationId,
- id_type::MerchantId,
+ Option<id_type::MerchantId>,
Option<id_type::ProfileId>,
)>,
> {
match entity_type {
- EntityType::Organization => Err(UserErrors::InvalidRoleOperation.into()),
+ EntityType::Organization => {
+ let Ok(org_id) =
+ id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone()))
+ else {
+ return Ok(None);
+ };
+
+ let user_roles = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id,
+ org_id: Some(&org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::InvitationSent),
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect::<HashSet<_>>();
+
+ if user_roles.len() > 1 {
+ return Ok(None);
+ }
+
+ if let Some(user_role) = user_roles.into_iter().next() {
+ let (_entity_id, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)?;
+
+ if entity_type != EntityType::Organization {
+ return Ok(None);
+ }
+
+ return Ok(Some((
+ user_role.org_id.ok_or(UserErrors::InternalServerError)?,
+ None,
+ None,
+ )));
+ }
+
+ Ok(None)
+ }
EntityType::Merchant => {
let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else {
return Ok(None);
@@ -298,7 +343,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
- merchant_id,
+ Some(merchant_id),
None,
)));
}
@@ -343,9 +388,11 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
return Ok(Some((
user_role.org_id.ok_or(UserErrors::InternalServerError)?,
- user_role
- .merchant_id
- .ok_or(UserErrors::InternalServerError)?,
+ Some(
+ user_role
+ .merchant_id
+ .ok_or(UserErrors::InternalServerError)?,
+ ),
Some(profile_id),
)));
}
| 2024-10-07T15:00:50Z |
## Description
<!-- Describe your changes in detail -->
Currently accepting invites for org_admin will not work. This PR fixes it.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 [#6254](https://github.com/juspay/hyperswitch/issues/6254)
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl 'http://localhost:8080/user/accept_invite_from_email' \
-H 'authorization: Bearer SPT with accept_invite_from_email' \
--data-raw '{"token":"email token"}'
```
Response:
```json
{
"token": "JWT",
"token_type": "user_info"
}
``` | b79f75a7ab9ed63a75defa2b3c5f9c170fca493e |
```
curl 'http://localhost:8080/user/accept_invite_from_email' \
-H 'authorization: Bearer SPT with accept_invite_from_email' \
--data-raw '{"token":"email token"}'
```
Response:
```json
{
"token": "JWT",
"token_type": "user_info"
}
```
| [
"crates/diesel_models/src/query/user_role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user_role.rs",
"crates/router/src/utils/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6122 | Bug: [REFACTOR]: [SHIFT4] Add amount conversion framework to Shift4
### :memo: Feature Description
Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows.
Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application.
### :hammer: Possible Implementation
- For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly.
- Connectors should invoke the `convert` function to receive the amount in their required format.
- Refer to the [connector documentation](https://dev.shift4.com/docs/api#cards) to determine the required amount format for each connector.
- You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context.
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/`
### :package: Have you spent some time checking if this feature request has been raised before?
- [ ] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :package: Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs
index 895487db3ba..08c23bc5710 100644
--- a/crates/router/src/connector/shift4.rs
+++ b/crates/router/src/connector/shift4.rs
@@ -1,8 +1,10 @@
pub mod transformers;
-use std::fmt::Debug;
-
-use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
+use common_utils::{
+ ext_traits::ByteSliceExt,
+ request::RequestContent,
+ types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
+};
use diesel_models::enums;
use error_stack::{report, ResultExt};
use transformers as shift4;
@@ -27,8 +29,18 @@ use crate::{
utils::BytesExt,
};
-#[derive(Debug, Clone)]
-pub struct Shift4;
+#[derive(Clone)]
+pub struct Shift4 {
+ amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
+}
+
+impl Shift4 {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &MinorUnitForConnector,
+ }
+ }
+}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Shift4
where
@@ -206,7 +218,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?;
+ let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -470,7 +488,21 @@ impl
req: &types::PaymentsPreProcessingRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount.ok_or_else(|| {
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "minor_amount",
+ }
+ })?,
+ req.request
+ .currency
+ .ok_or_else(|| errors::ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?,
+ )?;
+ let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?;
+ let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -559,7 +591,13 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?;
+ let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -641,7 +679,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = shift4::Shift4RefundRequest::try_from(req)?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?;
+ let connector_req = shift4::Shift4RefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 2210ab0a361..3b768151115 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -1,6 +1,6 @@
use api_models::payments;
use cards::CardNumber;
-use common_utils::pii::SecretSerdeValue;
+use common_utils::{pii::SecretSerdeValue, types::MinorUnit};
use error_stack::ResultExt;
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -23,11 +23,25 @@ trait Shift4AuthorizePreprocessingCommon {
fn get_router_return_url(&self) -> Option<String>;
fn get_email_optional(&self) -> Option<pii::Email>;
fn get_complete_authorize_url(&self) -> Option<String>;
- fn get_amount_required(&self) -> Result<i64, Error>;
fn get_currency_required(&self) -> Result<diesel_models::enums::Currency, Error>;
fn get_payment_method_data_required(&self) -> Result<domain::PaymentMethodData, Error>;
}
+pub struct Shift4RouterData<T> {
+ pub amount: MinorUnit,
+ pub router_data: T,
+}
+
+impl<T> TryFrom<(MinorUnit, T)> for Shift4RouterData<T> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
impl Shift4AuthorizePreprocessingCommon for types::PaymentsAuthorizeData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
@@ -37,10 +51,6 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsAuthorizeData {
self.complete_authorize_url.clone()
}
- fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>> {
- Ok(self.amount)
- }
-
fn get_currency_required(
&self,
) -> Result<diesel_models::enums::Currency, error_stack::Report<errors::ConnectorError>> {
@@ -70,10 +80,6 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsPreProcessingData {
self.complete_authorize_url.clone()
}
- fn get_amount_required(&self) -> Result<i64, Error> {
- self.get_amount()
- }
-
fn get_currency_required(&self) -> Result<diesel_models::enums::Currency, Error> {
self.get_currency()
}
@@ -95,7 +101,7 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsPreProcessingData {
}
#[derive(Debug, Serialize)]
pub struct Shift4PaymentsRequest {
- amount: String,
+ amount: MinorUnit,
currency: enums::Currency,
captured: bool,
#[serde(flatten)]
@@ -195,19 +201,19 @@ pub enum CardPayment {
CardToken(Secret<String>),
}
-impl<T, Req> TryFrom<&types::RouterData<T, Req, types::PaymentsResponseData>>
+impl<T, Req> TryFrom<&Shift4RouterData<&types::RouterData<T, Req, types::PaymentsResponseData>>>
for Shift4PaymentsRequest
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
- item: &types::RouterData<T, Req, types::PaymentsResponseData>,
+ item: &Shift4RouterData<&types::RouterData<T, Req, types::PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
- let submit_for_settlement = item.request.is_automatic_capture()?;
- let amount = item.request.get_amount_required()?.to_string();
- let currency = item.request.get_currency_required()?;
- let payment_method = Shift4PaymentMethod::try_from(item)?;
+ let submit_for_settlement = item.router_data.request.is_automatic_capture()?;
+ let amount = item.amount.to_owned();
+ let currency = item.router_data.request.get_currency_required()?;
+ let payment_method = Shift4PaymentMethod::try_from(item.router_data)?;
Ok(Self {
amount,
currency,
@@ -437,27 +443,33 @@ where
}
}
-impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>>
- for Shift4PaymentsRequest
+impl<T>
+ TryFrom<
+ &Shift4RouterData<
+ &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ >,
+ > for Shift4PaymentsRequest
{
type Error = Error;
fn try_from(
- item: &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ item: &Shift4RouterData<
+ &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>,
+ >,
) -> Result<Self, Self::Error> {
- match &item.request.payment_method_data {
+ match &item.router_data.request.payment_method_data {
Some(domain::PaymentMethodData::Card(_)) => {
let card_token: Shift4CardToken =
- to_connector_meta(item.request.connector_meta.clone())?;
+ to_connector_meta(item.router_data.request.connector_meta.clone())?;
Ok(Self {
- amount: item.request.amount.to_string(),
- currency: item.request.currency,
+ amount: item.amount.to_owned(),
+ currency: item.router_data.request.currency,
payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new(
CardsNon3DSRequest {
card: CardPayment::CardToken(card_token.id),
- description: item.description.clone(),
+ description: item.router_data.description.clone(),
},
)),
- captured: item.request.is_auto_capture()?,
+ captured: item.router_data.request.is_auto_capture()?,
})
}
Some(domain::PaymentMethodData::Wallet(_))
@@ -687,7 +699,7 @@ pub struct Token {
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct ThreeDSecureInfo {
- pub amount: i64,
+ pub amount: MinorUnit,
pub currency: String,
pub enrolled: bool,
#[serde(rename = "liabilityShift")]
@@ -814,15 +826,17 @@ impl<T, F>
#[serde(rename_all = "camelCase")]
pub struct Shift4RefundRequest {
charge_id: String,
- amount: i64,
+ amount: MinorUnit,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest {
+impl<F> TryFrom<&Shift4RouterData<&types::RefundsRouterData<F>>> for Shift4RefundRequest {
type Error = Error;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &Shift4RouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- charge_id: item.request.connector_transaction_id.clone(),
- amount: item.request.refund_amount,
+ charge_id: item.router_data.request.connector_transaction_id.clone(),
+ amount: item.amount.to_owned(),
})
}
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 5300e86afdb..18283834cf0 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -473,7 +473,9 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new())))
}
enums::Connector::Rapyd => Ok(ConnectorEnum::Old(Box::new(&connector::Rapyd))),
- enums::Connector::Shift4 => Ok(ConnectorEnum::Old(Box::new(&connector::Shift4))),
+ enums::Connector::Shift4 => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new())))
+ }
enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))),
enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))),
enums::Connector::Stripe => {
diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs
index fdaa1ebedef..ce10c9dad1a 100644
--- a/crates/router/tests/connectors/shift4.rs
+++ b/crates/router/tests/connectors/shift4.rs
@@ -15,7 +15,7 @@ impl utils::Connector for Shift4Test {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Shift4;
utils::construct_connector_data_old(
- Box::new(&Shift4),
+ Box::new(Shift4::new()),
types::Connector::Shift4,
types::api::GetToken::Connector,
None,
| 2024-10-07T11:52:12Z |
## Description
This PR adds amount conversion framework to Shift4, for sending to connector.
Resolves #6122
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
--> | 3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1 | [
"crates/router/src/connector/shift4.rs",
"crates/router/src/connector/shift4/transformers.rs",
"crates/router/src/types/api.rs",
"crates/router/tests/connectors/shift4.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-6249 | Bug: fix(users): max attempts for two-fa
- Previously, there was no limit on the number of failed attempts for TOTP and recovery code. With this PR, a maximum of 4 wrong attempts is introduced for both TOTP and recovery code. After 4 failed attempts, a cooldown period of 5 minutes applies for TOTP, and 10 minutes for the recovery code.
- A new endpoint is introduced to check the no of attempts of the user and also if the user has done two-fa recently . | diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index bb61a025180..4dc2a1a301a 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -18,8 +18,9 @@ use crate::user::{
ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest,
SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest,
SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse,
- UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest,
+ UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest,
+ VerifyTotpRequest,
};
#[cfg(feature = "recon")]
@@ -62,6 +63,7 @@ common_utils::impl_api_event_type!(
GetUserRoleDetailsResponseV2,
TokenResponse,
TwoFactorAuthStatusResponse,
+ TwoFactorStatus,
UserFromEmailRequest,
BeginTotpResponse,
VerifyRecoveryCodeRequest,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index d66f9f3bc03..089089038b8 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -196,6 +196,23 @@ pub struct TwoFactorAuthStatusResponse {
pub recovery_code: bool,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TwoFactorAuthAttempts {
+ pub is_completed: bool,
+ pub remaining_attempts: u8,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TwoFactorAuthStatusResponseWithAttempts {
+ pub totp: TwoFactorAuthAttempts,
+ pub recovery_code: TwoFactorAuthAttempts,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TwoFactorStatus {
+ pub status: Option<TwoFactorAuthStatusResponseWithAttempts>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 6ac2b08e6bb..2b90f9fa488 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -15,6 +15,10 @@ pub const TOTP_DIGITS: usize = 6;
pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
pub const TOTP_TOLERANCE: u8 = 1;
+/// Number of maximum attempts user has for totp
+pub const TOTP_MAX_ATTEMPTS: u8 = 4;
+/// Number of maximum attempts user has for recovery code
+pub const RECOVERY_CODE_MAX_ATTEMPTS: u8 = 4;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
@@ -23,6 +27,10 @@ pub const REDIS_TOTP_PREFIX: &str = "TOTP_";
pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_";
pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_";
pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes
+pub const REDIS_TOTP_ATTEMPTS_PREFIX: &str = "TOTP_ATTEMPTS_";
+pub const REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX: &str = "RC_ATTEMPTS_";
+pub const REDIS_TOTP_ATTEMPTS_TTL_IN_SECS: i64 = 5 * 60; // 5 mins
+pub const REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS: i64 = 10 * 60; // 10 mins
pub const REDIS_SSO_PREFIX: &str = "SSO_";
pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index e3c4bedab72..df4ce1d8148 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -90,6 +90,10 @@ pub enum UserErrors {
SSOFailed,
#[error("profile_id missing in JWT")]
JwtProfileIdMissing,
+ #[error("Maximum attempts reached for TOTP")]
+ MaxTotpAttemptsReached,
+ #[error("Maximum attempts reached for Recovery Code")]
+ MaxRecoveryCodeAttemptsReached,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -229,6 +233,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::JwtProfileIdMissing => {
AER::Unauthorized(ApiError::new(sub_code, 47, self.get_error_message(), None))
}
+ Self::MaxTotpAttemptsReached => {
+ AER::BadRequest(ApiError::new(sub_code, 48, self.get_error_message(), None))
+ }
+ Self::MaxRecoveryCodeAttemptsReached => {
+ AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None))
+ }
}
}
}
@@ -269,6 +279,8 @@ impl UserErrors {
Self::InvalidTotp => "Invalid TOTP",
Self::TotpRequired => "TOTP required",
Self::InvalidRecoveryCode => "Invalid Recovery Code",
+ Self::MaxTotpAttemptsReached => "Maximum attempts reached for TOTP",
+ Self::MaxRecoveryCodeAttemptsReached => "Maximum attempts reached for Recovery Code",
Self::TwoFactorAuthRequired => "Two factor auth required",
Self::TwoFactorAuthNotSetup => "Two factor auth not setup",
Self::TotpSecretNotFound => "TOTP secret not found",
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 046675f5200..6974287f2e1 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1686,6 +1686,13 @@ pub async fn verify_totp(
return Err(UserErrors::TotpNotSetup.into());
}
+ let user_totp_attempts =
+ tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?;
+
+ if user_totp_attempts >= consts::user::TOTP_MAX_ATTEMPTS {
+ return Err(UserErrors::MaxTotpAttemptsReached.into());
+ }
+
let user_totp_secret = user_from_db
.decrypt_and_get_totp_secret(&state)
.await?
@@ -1702,6 +1709,13 @@ pub async fn verify_totp(
.change_context(UserErrors::InternalServerError)?
!= req.totp.expose()
{
+ let _ = tfa_utils::insert_totp_attempts_in_redis(
+ &state,
+ &user_token.user_id,
+ user_totp_attempts + 1,
+ )
+ .await
+ .inspect_err(|error| logger::error!(?error));
return Err(UserErrors::InvalidTotp.into());
}
@@ -1856,15 +1870,31 @@ pub async fn verify_recovery_code(
return Err(UserErrors::TwoFactorAuthNotSetup.into());
}
+ let user_recovery_code_attempts =
+ tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?;
+
+ if user_recovery_code_attempts >= consts::user::RECOVERY_CODE_MAX_ATTEMPTS {
+ return Err(UserErrors::MaxRecoveryCodeAttemptsReached.into());
+ }
+
let mut recovery_codes = user_from_db
.get_recovery_codes()
.ok_or(UserErrors::InternalServerError)?;
- let matching_index = utils::user::password::get_index_for_correct_recovery_code(
+ let Some(matching_index) = utils::user::password::get_index_for_correct_recovery_code(
&req.recovery_code,
&recovery_codes,
)?
- .ok_or(UserErrors::InvalidRecoveryCode)?;
+ else {
+ let _ = tfa_utils::insert_recovery_code_attempts_in_redis(
+ &state,
+ &user_token.user_id,
+ user_recovery_code_attempts + 1,
+ )
+ .await
+ .inspect_err(|error| logger::error!(?error));
+ return Err(UserErrors::InvalidRecoveryCode.into());
+ };
tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?;
let _ = recovery_codes.remove(matching_index);
@@ -1924,10 +1954,17 @@ pub async fn terminate_two_factor_auth(
}
}
- let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::TOTP.into())?;
+ let current_flow = domain::CurrentFlow::new(user_token.clone(), domain::SPTFlow::TOTP.into())?;
let next_flow = current_flow.next(user_from_db, &state).await?;
let token = next_flow.get_token(&state).await?;
+ let _ = tfa_utils::delete_totp_attempts_from_redis(&state, &user_token.user_id)
+ .await
+ .inspect_err(|error| logger::error!(?error));
+ let _ = tfa_utils::delete_recovery_code_attempts_from_redis(&state, &user_token.user_id)
+ .await
+ .inspect_err(|error| logger::error!(?error));
+
auth::cookies::set_cookie_response(
user_api::TokenResponse {
token: token.clone(),
@@ -1950,6 +1987,40 @@ pub async fn check_two_factor_auth_status(
))
}
+pub async fn check_two_factor_auth_status_with_attempts(
+ state: SessionState,
+ user_token: auth::UserIdFromAuth,
+) -> UserResponse<user_api::TwoFactorStatus> {
+ let user_from_db: domain::UserFromStorage = state
+ .global_store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+ if user_from_db.get_totp_status() == TotpStatus::NotSet {
+ return Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
+ status: None,
+ }));
+ };
+
+ let totp = user_api::TwoFactorAuthAttempts {
+ is_completed: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
+ remaining_attempts: consts::user::TOTP_MAX_ATTEMPTS
+ - tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?,
+ };
+ let recovery_code = user_api::TwoFactorAuthAttempts {
+ is_completed: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?,
+ remaining_attempts: consts::user::RECOVERY_CODE_MAX_ATTEMPTS
+ - tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?,
+ };
+ Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
+ status: Some(user_api::TwoFactorAuthStatusResponseWithAttempts {
+ totp,
+ recovery_code,
+ }),
+ }))
+}
+
pub async fn create_user_authentication_method(
state: SessionState,
req: user_api::CreateUserAuthenticationMethodRequest,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 54e4471b057..b9175fa9bbd 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1849,7 +1849,12 @@ impl User {
// Two factor auth routes
route = route.service(
web::scope("/2fa")
+ // TODO: to be deprecated
.service(web::resource("").route(web::get().to(user::check_two_factor_auth_status)))
+ .service(
+ web::resource("/v2")
+ .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),
+ )
.service(
web::scope("/totp")
.service(web::resource("/begin").route(web::get().to(user::totp_begin)))
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 16786e71768..e07a2fa10ef 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -682,6 +682,23 @@ pub async fn check_two_factor_auth_status(
.await
}
+pub async fn check_two_factor_auth_status_with_attempts(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::TwoFactorAuthStatus;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::check_two_factor_auth_status_with_attempts(state, user),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn get_sso_auth_url(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index bebe58ebd86..73d692a00e0 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -139,3 +139,90 @@ pub async fn delete_recovery_code_from_redis(
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
+
+fn get_totp_attempts_key(user_id: &str) -> String {
+ format!("{}{}", consts::user::REDIS_TOTP_ATTEMPTS_PREFIX, user_id)
+}
+fn get_recovery_code_attempts_key(user_id: &str) -> String {
+ format!(
+ "{}{}",
+ consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX,
+ user_id
+ )
+}
+
+pub async fn insert_totp_attempts_in_redis(
+ state: &SessionState,
+ user_id: &str,
+ user_totp_attempts: u8,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .set_key_with_expiry(
+ &get_totp_attempts_key(user_id),
+ user_totp_attempts,
+ consts::user::REDIS_TOTP_ATTEMPTS_TTL_IN_SECS,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<u8>>(&get_totp_attempts_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|v| v.unwrap_or(0))
+}
+
+pub async fn insert_recovery_code_attempts_in_redis(
+ state: &SessionState,
+ user_id: &str,
+ user_recovery_code_attempts: u8,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .set_key_with_expiry(
+ &get_recovery_code_attempts_key(user_id),
+ user_recovery_code_attempts,
+ consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
+pub async fn get_recovery_code_attempts_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<u8> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|v| v.unwrap_or(0))
+}
+
+pub async fn delete_totp_attempts_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .delete_key(&get_totp_attempts_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
+
+pub async fn delete_recovery_code_attempts_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .delete_key(&get_recovery_code_attempts_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
| 2024-10-07T10:19:31Z |
## Description
<!-- Describe your changes in detail -->
- Previously, there was no limit on the number of failed attempts for TOTP and recovery code. With this PR, a maximum of 4 wrong attempts is introduced for both TOTP and recovery code. After 4 failed attempts, a cooldown period of 5 minutes applies for TOTP, and 10 minutes for the recovery code.
- A new endpoint is introduced to check the no of attempts of the user and also if the user has done two-fa recently .
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request :
```
curl --location 'http://localhost:8080/user/2fa/v2' \
--header 'Authorization: Bearer JWT'
```
Response:
- If the user has not set twofa
```
{
"status": null
}
```
- If the user has twofa set and no attempts is remaining for both recovery code and totp
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 0
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 0
}
}
}
```
- If the user has twofa set and no attempts is remaining for recovery code
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 4
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 0
}
}
}
```
- If the user has twofa set and no attempts is remaining for totp
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 0
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 4
}
}
}
```
After 4 wrong recovery code attempts , `2fa/recovery_code/verify` will throw `UR_49` error
Request :
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'authorization: Bearer JWT' \
--data '{"recovery_code":"some_invalid_recovery_code"}'
```
Response :
```
{
"error": {
"type": "invalid_request",
"message": "Maximum recovery code attempts per user reached",
"code": "UR_49"
}
}
```
After 4 wrong totp attempts , `2fa/recovery_code/verify` will throw `UR_48` error
Request :
```
curl 'http://localhost:8080/user/2fa/totp/verify' \
-H 'authorization: Bearer JWT' \
--data-raw '{"totp":"some_invalid_totp"}'
```
Response :
```
{
"error": {
"type": "invalid_request",
"message": "Maximum totp attempts per user reached",
"code": "UR_48"
}
}
``` | 55a97cc952aedd67451ed3785792e00d74f357ff |
Request :
```
curl --location 'http://localhost:8080/user/2fa/v2' \
--header 'Authorization: Bearer JWT'
```
Response:
- If the user has not set twofa
```
{
"status": null
}
```
- If the user has twofa set and no attempts is remaining for both recovery code and totp
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 0
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 0
}
}
}
```
- If the user has twofa set and no attempts is remaining for recovery code
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 4
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 0
}
}
}
```
- If the user has twofa set and no attempts is remaining for totp
```
{
"status": {
"totp": {
"is_completed": false,
"remaining_attempts": 0
},
"recovery_code": {
"is_completed": false,
"remaining_attempts": 4
}
}
}
```
After 4 wrong recovery code attempts , `2fa/recovery_code/verify` will throw `UR_49` error
Request :
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'authorization: Bearer JWT' \
--data '{"recovery_code":"some_invalid_recovery_code"}'
```
Response :
```
{
"error": {
"type": "invalid_request",
"message": "Maximum recovery code attempts per user reached",
"code": "UR_49"
}
}
```
After 4 wrong totp attempts , `2fa/recovery_code/verify` will throw `UR_48` error
Request :
```
curl 'http://localhost:8080/user/2fa/totp/verify' \
-H 'authorization: Bearer JWT' \
--data-raw '{"totp":"some_invalid_totp"}'
```
Response :
```
{
"error": {
"type": "invalid_request",
"message": "Maximum totp attempts per user reached",
"code": "UR_48"
}
}
```
| [
"crates/api_models/src/events/user.rs",
"crates/api_models/src/user.rs",
"crates/router/src/consts/user.rs",
"crates/router/src/core/errors/user.rs",
"crates/router/src/core/user.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/utils/user/two_factor_auth.r... | |
juspay/hyperswitch | juspay__hyperswitch-6260 | Bug: Add support for network transaction id and card details based MIT
Support needs to be added in order to accept the card details and network transaction id in `recurring_details` for an MIT. This will be only in the Sever-to-Server call where the customer is off_session and merchant is initiating the transaction who is a PCI entity and has stored his customer card details and network transaction id.
Support needs to be added to accept card details and the network transaction ID in `recurring_details` for a Merchant Initiated Transaction (MIT). This will only apply to the Server-to-Server call, where the customer is off-session, and the merchant, as a PCI entity, initiates the transaction using stored customer card details and the network transaction ID.
As in this case we are not creating customer or any payment method entries in hyperswitch we have separate `proxy_for_payments_operation_core` to decouple this flow from the actual payments flow. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 44ac1d3e08d..99055a2c6b5 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -10093,6 +10093,77 @@
}
}
},
+ "NetworkTransactionIdAndCardDetails": {
+ "type": "object",
+ "required": [
+ "card_number",
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name",
+ "network_transaction_id"
+ ],
+ "properties": {
+ "card_number": {
+ "type": "string",
+ "description": "The card number",
+ "example": "4242424242424242"
+ },
+ "card_exp_month": {
+ "type": "string",
+ "description": "The card's expiry month",
+ "example": "24"
+ },
+ "card_exp_year": {
+ "type": "string",
+ "description": "The card's expiry year",
+ "example": "24"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "The card holder's name",
+ "example": "John Test"
+ },
+ "card_issuer": {
+ "type": "string",
+ "description": "The name of the issuer of card",
+ "example": "chase",
+ "nullable": true
+ },
+ "card_network": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardNetwork"
+ }
+ ],
+ "nullable": true
+ },
+ "card_type": {
+ "type": "string",
+ "example": "CREDIT",
+ "nullable": true
+ },
+ "card_issuing_country": {
+ "type": "string",
+ "example": "INDIA",
+ "nullable": true
+ },
+ "bank_code": {
+ "type": "string",
+ "example": "JP_AMEX",
+ "nullable": true
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "The card holder's nick name",
+ "example": "John Test",
+ "nullable": true
+ },
+ "network_transaction_id": {
+ "type": "string",
+ "description": "The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),\nwhere `setup_future_usage` is set to `off_session`."
+ }
+ }
+ },
"NextActionCall": {
"type": "string",
"enum": [
@@ -17898,6 +17969,24 @@
"$ref": "#/components/schemas/ProcessorPaymentToken"
}
}
+ },
+ {
+ "type": "object",
+ "required": [
+ "type",
+ "data"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "network_transaction_id_and_card_details"
+ ]
+ },
+ "data": {
+ "$ref": "#/components/schemas/NetworkTransactionIdAndCardDetails"
+ }
+ }
}
],
"description": "Details required for recurring payment",
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index fe5b053b180..2d61a630988 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -121,6 +121,10 @@ pub enum RecurringDetails {
MandateId(String),
PaymentMethodId(String),
ProcessorPaymentToken(ProcessorPaymentToken),
+
+ /// Network transaction ID and Card Details for MIT payments when payment_method_data
+ /// is not stored in the application
+ NetworkTransactionIdAndCardDetails(NetworkTransactionIdAndCardDetails),
}
/// Processor payment token for MIT payments where payment_method_data is not available
@@ -130,3 +134,54 @@ pub struct ProcessorPaymentToken {
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
+pub struct NetworkTransactionIdAndCardDetails {
+ /// The card number
+ #[schema(value_type = String, example = "4242424242424242")]
+ pub card_number: cards::CardNumber,
+
+ /// The card's expiry month
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_month: Secret<String>,
+
+ /// The card's expiry year
+ #[schema(value_type = String, example = "24")]
+ pub card_exp_year: Secret<String>,
+
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The name of the issuer of card
+ #[schema(example = "chase")]
+ pub card_issuer: Option<String>,
+
+ /// The card network for the card
+ #[schema(value_type = Option<CardNetwork>, example = "Visa")]
+ pub card_network: Option<api_enums::CardNetwork>,
+
+ #[schema(example = "CREDIT")]
+ pub card_type: Option<String>,
+
+ #[schema(example = "INDIA")]
+ pub card_issuing_country: Option<String>,
+
+ #[schema(example = "JP_AMEX")]
+ pub bank_code: Option<String>,
+
+ /// The card holder's nick name
+ #[schema(value_type = Option<String>, example = "John Test")]
+ pub nick_name: Option<Secret<String>>,
+
+ /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction),
+ /// where `setup_future_usage` is set to `off_session`.
+ #[schema(value_type = String)]
+ pub network_transaction_id: Secret<String>,
+}
+
+impl RecurringDetails {
+ pub fn is_network_transaction_id_and_card_details_flow(self) -> bool {
+ matches!(self, Self::NetworkTransactionIdAndCardDetails(_))
+ }
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a758d457858..285a24b445b 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1125,6 +1125,15 @@ pub struct MandateIds {
pub mandate_reference_id: Option<MandateReferenceId>,
}
+impl MandateIds {
+ pub fn is_network_transaction_id_flow(&self) -> bool {
+ matches!(
+ self.mandate_reference_id,
+ Some(MandateReferenceId::NetworkMandateId(_))
+ )
+ }
+}
+
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum MandateReferenceId {
ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector
@@ -4961,7 +4970,7 @@ pub struct PazeMetadata {
pub enum SamsungPayCombinedMetadata {
// This is to support the Samsung Pay decryption flow with application credentials,
// where the private key, certificates, or any other information required for decryption
- // will be obtained from the environment variables.
+ // will be obtained from the application configuration.
ApplicationCredentials(SamsungPayApplicationCredentials),
MerchantCredentials(SamsungPayMerchantCredentials),
}
diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
index b8c75e3c4db..4212f7168db 100644
--- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
@@ -224,10 +224,13 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("bambora"),
- )
- .into()),
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("bambora"),
+ )
+ .into())
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index 03a585f76bd..4440346db6b 100644
--- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -86,9 +86,12 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("CryptoPay"),
- )),
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("CryptoPay"),
+ ))
+ }
}?;
Ok(cryptopay_request)
}
diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
index 385601294b3..d21fa481579 100644
--- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
@@ -171,9 +171,12 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
+ ))?
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
index b2cbd570b4f..cdcd82f5b4f 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
@@ -199,7 +199,8 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => {
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("fiserv"),
))
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index c4ca017cec7..c06f0a208e5 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -413,10 +413,13 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("fiuu"),
- )
- .into()),
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("fiuu"),
+ )
+ .into())
+ }
}?;
Ok(Self {
diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
index 772f2af209e..2e3919cfc48 100644
--- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
@@ -101,9 +101,12 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- get_unimplemented_payment_method_error_message("globepay"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("globepay"),
+ ))?
+ }
};
let description = item.get_description()?;
Ok(Self {
diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
index 90380d02321..a01e2cf918d 100644
--- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
@@ -181,9 +181,12 @@ impl TryFrom<&SetupMandateRouterData> for HelcimVerifyRequest {
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
+ ))?
+ }
}
}
}
@@ -275,9 +278,12 @@ impl TryFrom<&HelcimRouterData<&PaymentsAuthorizeRouterData>> for HelcimPayments
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Helcim"),
+ ))?
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
index 54856d4dba5..1677343fe38 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
@@ -413,9 +413,12 @@ impl TryFrom<&NexixpayRouterData<&PaymentsAuthorizeRouterData>> for NexixpayPaym
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- get_unimplemented_payment_method_error_message("nexixpay"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ get_unimplemented_payment_method_error_message("nexixpay"),
+ ))?
+ }
}
}
}
@@ -828,7 +831,8 @@ impl TryFrom<&NexixpayRouterData<&PaymentsCompleteAuthorizeRouterData>>
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => {
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("nexixpay"),
)
diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
index 5ea64f8b958..770688a3468 100644
--- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
@@ -126,11 +126,14 @@ impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotSupported {
- message: utils::SELECTED_PAYMENT_METHOD.to_string(),
- connector: "powertranz",
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "powertranz",
+ }
+ .into())
}
- .into()),
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index ad09e7445d4..b2151c524be 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -177,9 +177,12 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?
+ }
}
}
}
@@ -294,9 +297,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index 686178e9621..0f112566796 100644
--- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -124,9 +124,12 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Stax"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Stax"),
+ ))?
+ }
}
}
}
@@ -275,9 +278,12 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Stax"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Stax"),
+ ))?
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
index 8d96058c233..e97cf228729 100644
--- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
@@ -90,9 +90,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest {
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("tsys"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("tsys"),
+ ))?
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 953b6316ff8..e04eae63b4c 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -148,10 +148,13 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Volt"),
- )
- .into()),
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Volt"),
+ )
+ .into())
+ }
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
index 33c865c3b5f..09ffac81425 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
@@ -218,38 +218,40 @@ impl
&RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
- let payment_data = match &item.router_data.request.payment_method_data {
- PaymentMethodData::Card(card) => {
- let card_holder_name = item.router_data.get_optional_billing_full_name();
- WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(make_card_request(
- &item.router_data.request,
- card,
- card_holder_name,
- )?))
- }
- PaymentMethodData::BankRedirect(bank_redirect) => {
- WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
- make_bank_redirect_request(item.router_data, bank_redirect)?,
- ))
- }
- PaymentMethodData::CardRedirect(_)
- | PaymentMethodData::Wallet(_)
- | PaymentMethodData::PayLater(_)
- | PaymentMethodData::BankDebit(_)
- | PaymentMethodData::BankTransfer(_)
- | PaymentMethodData::Crypto(_)
- | PaymentMethodData::MandatePayment
- | PaymentMethodData::Reward
- | PaymentMethodData::RealTimePayment(_)
- | PaymentMethodData::Upi(_)
- | PaymentMethodData::Voucher(_)
- | PaymentMethodData::GiftCard(_)
- | PaymentMethodData::OpenBanking(_)
- | PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("worldline"),
- ))?,
- };
+ let payment_data =
+ match &item.router_data.request.payment_method_data {
+ PaymentMethodData::Card(card) => {
+ let card_holder_name = item.router_data.get_optional_billing_full_name();
+ WorldlinePaymentMethod::CardPaymentMethodSpecificInput(Box::new(
+ make_card_request(&item.router_data.request, card, card_holder_name)?,
+ ))
+ }
+ PaymentMethodData::BankRedirect(bank_redirect) => {
+ WorldlinePaymentMethod::RedirectPaymentMethodSpecificInput(Box::new(
+ make_bank_redirect_request(item.router_data, bank_redirect)?,
+ ))
+ }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("worldline"),
+ ))?
+ }
+ };
let billing_address = item.router_data.get_billing()?;
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 66b8081b0f2..0134253f2f9 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -1861,6 +1861,7 @@ pub enum PaymentMethodDataType {
VietQr,
OpenBanking,
NetworkToken,
+ NetworkTransactionIdAndCardDetails,
}
impl From<PaymentMethodData> for PaymentMethodDataType {
@@ -1868,6 +1869,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType {
match pm_data {
PaymentMethodData::Card(_) => Self::Card,
PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
+ PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::NetworkTransactionIdAndCardDetails,
PaymentMethodData::CardRedirect(card_redirect_data) => {
match card_redirect_data {
hyperswitch_domain_models::payment_method_data::CardRedirectData::Knet {} => Self::Knet,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 3ccfabf021c..5c4979ab49d 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1,4 +1,7 @@
-use api_models::payments::{additional_info as payment_additional_types, ExtendedCardInfo};
+use api_models::{
+ mandates,
+ payments::{additional_info as payment_additional_types, ExtendedCardInfo},
+};
use common_enums::enums as api_enums;
use common_utils::{
id_type,
@@ -16,6 +19,7 @@ use time::Date;
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum PaymentMethodData {
Card(Card),
+ CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
@@ -43,7 +47,9 @@ pub enum ApplePayFlow {
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
- Self::Card(_) | Self::NetworkToken(_) => Some(common_enums::PaymentMethod::Card),
+ Self::Card(_) | Self::NetworkToken(_) | Self::CardDetailsForNetworkTransactionId(_) => {
+ Some(common_enums::PaymentMethod::Card)
+ }
Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
@@ -76,6 +82,62 @@ pub struct Card {
pub nick_name: Option<Secret<String>>,
}
+#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
+pub struct CardDetailsForNetworkTransactionId {
+ pub card_number: cards::CardNumber,
+ pub card_exp_month: Secret<String>,
+ pub card_exp_year: Secret<String>,
+ pub card_issuer: Option<String>,
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_type: Option<String>,
+ pub card_issuing_country: Option<String>,
+ pub bank_code: Option<String>,
+ pub nick_name: Option<Secret<String>>,
+}
+
+impl CardDetailsForNetworkTransactionId {
+ pub fn get_nti_and_card_details_for_mit_flow(
+ recurring_details: mandates::RecurringDetails,
+ ) -> Option<(api_models::payments::MandateReferenceId, Self)> {
+ let network_transaction_id_and_card_details = match recurring_details {
+ mandates::RecurringDetails::NetworkTransactionIdAndCardDetails(
+ network_transaction_id_and_card_details,
+ ) => Some(network_transaction_id_and_card_details),
+ mandates::RecurringDetails::MandateId(_)
+ | mandates::RecurringDetails::PaymentMethodId(_)
+ | mandates::RecurringDetails::ProcessorPaymentToken(_) => None,
+ }?;
+
+ let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(
+ network_transaction_id_and_card_details
+ .network_transaction_id
+ .peek()
+ .to_string(),
+ );
+
+ Some((
+ mandate_reference_id,
+ network_transaction_id_and_card_details.clone().into(),
+ ))
+ }
+}
+
+impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId {
+ fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self {
+ Self {
+ card_number: card_details_for_nti.card_number,
+ card_exp_month: card_details_for_nti.card_exp_month,
+ card_exp_year: card_details_for_nti.card_exp_year,
+ card_issuer: card_details_for_nti.card_issuer,
+ card_network: card_details_for_nti.card_network,
+ card_type: card_details_for_nti.card_type,
+ card_issuing_country: card_details_for_nti.card_issuing_country,
+ bank_code: card_details_for_nti.bank_code,
+ nick_name: card_details_for_nti.nick_name,
+ }
+ }
+}
+
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum CardRedirectData {
Knet {},
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 24fbadc0a59..27564569c3b 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -494,6 +494,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
+ api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index bc44068030b..deca42f17e5 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -386,6 +386,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
+ api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::payments::GooglePaySessionResponse,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index abd99fae18c..5e803b593ee 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -440,7 +440,8 @@ impl TryFrom<&AciRouterData<&types::PaymentsAuthorizeRouterData>> for AciPayment
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 4cc392c57bc..ca13e57e401 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1588,7 +1588,8 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?
@@ -2581,19 +2582,30 @@ impl<'a>
}
payments::MandateReferenceId::NetworkMandateId(network_mandate_id) => {
match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref card) => {
- let brand = match card.card_network.clone().and_then(get_adyen_card_network)
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(
+ ref card_details_for_network_transaction_id,
+ ) => {
+ let brand = match card_details_for_network_transaction_id
+ .card_network
+ .clone()
+ .and_then(get_adyen_card_network)
{
Some(card_network) => card_network,
- None => CardBrand::try_from(&card.get_card_issuer()?)?,
+ None => CardBrand::try_from(
+ &card_details_for_network_transaction_id.get_card_issuer()?,
+ )?,
};
let card_holder_name = item.router_data.get_optional_billing_full_name();
let adyen_card = AdyenCard {
payment_type: PaymentType::Scheme,
- number: card.card_number.clone(),
- expiry_month: card.card_exp_month.clone(),
- expiry_year: card.card_exp_year.clone(),
+ number: card_details_for_network_transaction_id.card_number.clone(),
+ expiry_month: card_details_for_network_transaction_id
+ .card_exp_month
+ .clone(),
+ expiry_year: card_details_for_network_transaction_id
+ .card_exp_year
+ .clone(),
cvc: None,
holder_name: card_holder_name,
brand: Some(brand),
@@ -2616,7 +2628,8 @@ impl<'a>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::Card(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Network tokenization for payment method".to_string(),
connector: "Adyen",
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 868a4767c31..e38999d495b 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -206,7 +206,8 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("airwallex"),
))
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index e352d8b79bc..903470ae952 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -344,7 +344,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
@@ -530,7 +531,8 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
@@ -590,7 +592,8 @@ impl
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index ab6367eeb6e..ad75328322d 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -324,7 +324,8 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
@@ -1097,7 +1098,8 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Bank of America",
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index c6f2be9dbfc..6b21014cdd5 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -104,7 +104,8 @@ impl TryFrom<&types::TokenizationRouterData> for BillwerkTokenRequest {
| domain::payments::PaymentMethodData::GiftCard(_)
| domain::payments::PaymentMethodData::OpenBanking(_)
| domain::payments::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("billwerk"),
)
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index b156aafb6ef..39be2517e4b 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -229,7 +229,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method via Token flow through bluesnap".to_string(),
)
@@ -396,7 +397,8 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
))
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index a48e49a10cc..bc9eb4e3722 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -112,7 +112,8 @@ impl TryFrom<&BokuRouterData<&types::PaymentsAuthorizeRouterData>> for BokuPayme
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("boku"),
))?
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 29f741d8bdc..b7515a964bb 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -310,7 +310,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
@@ -1104,7 +1105,8 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
)
@@ -1715,7 +1717,8 @@ fn get_braintree_redirect_form(
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => Err(
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Err(
errors::ConnectorError::NotImplemented("given payment method".to_owned()),
)?,
},
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 2950fdb6bd1..3e951b3ac86 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -135,7 +135,8 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
@@ -380,7 +381,8 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
))
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 8a6c3c075ff..4db35abec86 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -12,7 +12,6 @@ use common_utils::{
types::SemanticVersion,
};
use error_stack::ResultExt;
-use josekit::jwt::decode_header;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -251,7 +250,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?
@@ -1245,6 +1245,89 @@ impl
}
}
+impl
+ TryFrom<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
+ )> for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, ccard): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let email = item
+ .router_data
+ .get_billing_email()
+ .or(item.router_data.request.get_email())?;
+ let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
+ let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
+
+ let card_issuer = ccard.get_card_issuer();
+ let card_type = match card_issuer {
+ Ok(issuer) => Some(String::from(issuer)),
+ Err(_) => None,
+ };
+
+ let payment_information = PaymentInformation::Cards(Box::new(CardPaymentInformation {
+ card: Card {
+ number: ccard.card_number,
+ expiration_month: ccard.card_exp_month,
+ expiration_year: ccard.card_exp_year,
+ security_code: None,
+ card_type: card_type.clone(),
+ },
+ }));
+
+ let processing_information = ProcessingInformation::try_from((item, None, card_type))?;
+ let client_reference_information = ClientReferenceInformation::from(item);
+ let merchant_defined_information = item
+ .router_data
+ .request
+ .metadata
+ .clone()
+ .map(Vec::<MerchantDefinedInformation>::foreign_from);
+
+ let consumer_authentication_information = item
+ .router_data
+ .request
+ .authentication_data
+ .as_ref()
+ .map(|authn_data| {
+ let (ucaf_authentication_data, cavv) =
+ if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) {
+ (Some(Secret::new(authn_data.cavv.clone())), None)
+ } else {
+ (None, Some(authn_data.cavv.clone()))
+ };
+ CybersourceConsumerAuthInformation {
+ ucaf_collection_indicator: None,
+ cavv,
+ ucaf_authentication_data,
+ xid: Some(authn_data.threeds_server_transaction_id.clone()),
+ directory_server_transaction_id: authn_data
+ .ds_trans_id
+ .clone()
+ .map(Secret::new),
+ specification_version: None,
+ pa_specification_version: Some(authn_data.message_version.clone()),
+ veres_enrolled: Some("Y".to_string()),
+ }
+ });
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ consumer_authentication_information,
+ merchant_defined_information,
+ })
+ }
+}
+
impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
@@ -1690,9 +1773,10 @@ impl
fn get_samsung_pay_fluid_data_value(
samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData,
) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> {
- let samsung_pay_header = decode_header(samsung_pay_token_data.data.clone().peek())
- .change_context(errors::ConnectorError::RequestEncodingFailed)
- .attach_printable("Failed to decode samsung pay header")?;
+ let samsung_pay_header =
+ josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to decode samsung pay header")?;
let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str());
@@ -1871,6 +1955,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
domain::PaymentMethodData::NetworkToken(token_data) => {
Self::try_from((item, token_data))
}
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card) => {
+ Self::try_from((item, card))
+ }
domain::PaymentMethodData::CardRedirect(_)
| domain::PaymentMethodData::PayLater(_)
| domain::PaymentMethodData::BankRedirect(_)
@@ -1995,7 +2082,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -2718,7 +2806,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
@@ -2832,7 +2921,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs
index afc9288b656..b28504a1d83 100644
--- a/crates/router/src/connector/datatrans/transformers.rs
+++ b/crates/router/src/connector/datatrans/transformers.rs
@@ -189,7 +189,8 @@ impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message("Datatrans"),
))?
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index d9407b41011..79b90d685ee 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -135,7 +135,8 @@ impl TryFrom<&ForteRouterData<&types::PaymentsAuthorizeRouterData>> for FortePay
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Forte"),
))?
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index 4982aaf4d88..c0360a94a51 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -248,7 +248,8 @@ impl TryFrom<&types::TokenizationRouterData> for CustomerBankAccount {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Gocardless"),
)
@@ -420,7 +421,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 9f3cb9fe6e8..de92168036c 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -207,7 +207,8 @@ impl
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("iatapay"),
))?
diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs
index 0cd070c2053..41c41408381 100644
--- a/crates/router/src/connector/itaubank/transformers.rs
+++ b/crates/router/src/connector/itaubank/transformers.rs
@@ -120,7 +120,8 @@ impl TryFrom<&ItaubankRouterData<&types::PaymentsAuthorizeRouterData>> for Itaub
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method through itaubank".to_string(),
)
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 2c3d3651284..0c362d26edf 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -654,7 +654,8 @@ impl
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(report!(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message(
req.connector.as_str(),
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 92b6b45785d..03c63d66795 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -197,7 +197,8 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Mifinity"),
)
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index e0146bf2eda..9db1cb3701a 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -610,7 +610,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
@@ -793,7 +794,8 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 5bf72133384..6cf35f5d87d 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -628,9 +628,12 @@ fn get_payment_details_and_product(
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("nexinets"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("nexinets"),
+ ))?
+ }
}
}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 57b04cdca17..af2a9fe56bb 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -587,7 +587,8 @@ impl
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nmi"),
)
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 99e04018632..5c3de332b70 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -355,7 +355,8 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
conn_utils::get_unimplemented_payment_method_error_message("Noon"),
))
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index d9728174f84..d1d7122f49e 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -999,7 +999,8 @@ where
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
)
@@ -1203,6 +1204,7 @@ impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)>
| Some(domain::PaymentMethodData::OpenBanking(_))
| Some(domain::PaymentMethodData::CardToken(..))
| Some(domain::PaymentMethodData::NetworkToken(..))
+ | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
)),
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index dcb4e201e8b..16a76301ede 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -58,7 +58,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Opayo"),
)
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 8c2ad2ef979..685bf3c0fbb 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -262,7 +262,8 @@ fn get_payment_method_data(
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Payeezy"),
))?
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index b4aa66a1c49..4eac0a6f94d 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -433,7 +433,8 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => {
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}
@@ -679,9 +680,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("payme"),
- ))?,
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("payme"),
+ ))?
+ }
}
}
}
@@ -744,6 +748,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
+ | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
@@ -784,7 +789,8 @@ impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest {
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
- | PaymentMethodData::NetworkToken(_) => {
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Tokenize Flow".to_string()).into())
}
}
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 41fd533309e..b51357a42af 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -548,7 +548,8 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index 919fe25bdd8..32d651787b6 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -143,7 +143,8 @@ impl TryFrom<&PlacetopayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Placetopay"),
)
diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs
index 621c0969aff..fde72cac100 100644
--- a/crates/router/src/connector/razorpay/transformers.rs
+++ b/crates/router/src/connector/razorpay/transformers.rs
@@ -400,7 +400,8 @@ impl
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
}
}?;
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index e206fe0e0ae..2210ab0a361 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -249,7 +249,8 @@ where
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
@@ -475,6 +476,7 @@ impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::Payme
| Some(domain::PaymentMethodData::OpenBanking(_))
| Some(domain::PaymentMethodData::CardToken(_))
| Some(domain::PaymentMethodData::NetworkToken(_))
+ | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 68bab815d65..63720696ef4 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1347,7 +1347,8 @@ fn create_stripe_payment_method(
| domain::PaymentMethodData::MandatePayment
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
@@ -1724,20 +1725,28 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent
});
let payment_data = match item.request.payment_method_data {
- domain::payments::PaymentMethodData::Card(ref card) => {
- StripePaymentMethodData::Card(StripeCardData {
- payment_method_data_type: StripePaymentMethodType::Card,
- payment_method_data_card_number: card.card_number.clone(),
- payment_method_data_card_exp_month: card.card_exp_month.clone(),
- payment_method_data_card_exp_year: card.card_exp_year.clone(),
- payment_method_data_card_cvc: None,
- payment_method_auth_type: None,
- payment_method_data_card_preferred_network: card
+ domain::payments::PaymentMethodData::CardDetailsForNetworkTransactionId(
+ ref card_details_for_network_transaction_id,
+ ) => StripePaymentMethodData::Card(StripeCardData {
+ payment_method_data_type: StripePaymentMethodType::Card,
+ payment_method_data_card_number:
+ card_details_for_network_transaction_id.card_number.clone(),
+ payment_method_data_card_exp_month:
+ card_details_for_network_transaction_id
+ .card_exp_month
+ .clone(),
+ payment_method_data_card_exp_year:
+ card_details_for_network_transaction_id
+ .card_exp_year
+ .clone(),
+ payment_method_data_card_cvc: None,
+ payment_method_auth_type: None,
+ payment_method_data_card_preferred_network:
+ card_details_for_network_transaction_id
.card_network
.clone()
.and_then(get_stripe_card_network),
- })
- }
+ }),
domain::payments::PaymentMethodData::CardRedirect(_)
| domain::payments::PaymentMethodData::Wallet(_)
| domain::payments::PaymentMethodData::PayLater(_)
@@ -1753,7 +1762,8 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent
| domain::payments::PaymentMethodData::GiftCard(_)
| domain::payments::PaymentMethodData::OpenBanking(_)
| domain::payments::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::Card(_) => {
Err(errors::ConnectorError::NotSupported {
message: "Network tokenization for payment method".to_string(),
connector: "Stripe",
@@ -3369,6 +3379,7 @@ impl
| Some(domain::PaymentMethodData::OpenBanking(..))
| Some(domain::PaymentMethodData::CardToken(..))
| Some(domain::PaymentMethodData::NetworkToken(..))
+ | Some(domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
@@ -3823,7 +3834,8 @@ impl
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
))?
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index d05db4d28ab..fbff19fd0ad 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -435,7 +435,8 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 31afb0adf11..ea19acb76da 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1439,6 +1439,81 @@ impl CardData for payouts::CardPayout {
}
}
+impl CardData
+ for hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId
+{
+ fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let binding = self.card_exp_year.clone();
+ let year = binding.peek();
+ Ok(Secret::new(
+ year.get(year.len() - 2..)
+ .ok_or(errors::ConnectorError::RequestEncodingFailed)?
+ .to_string(),
+ ))
+ }
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
+ get_card_issuer(self.card_number.peek())
+ }
+ fn get_card_expiry_month_year_2_digit_with_delimiter(
+ &self,
+ delimiter: String,
+ ) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?;
+ Ok(Secret::new(format!(
+ "{}{}{}",
+ self.card_exp_month.peek(),
+ delimiter,
+ year.peek()
+ )))
+ }
+ fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
+ let year = self.get_expiry_year_4_digit();
+ Secret::new(format!(
+ "{}{}{}",
+ year.peek(),
+ delimiter,
+ self.card_exp_month.peek()
+ ))
+ }
+ fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
+ let year = self.get_expiry_year_4_digit();
+ Secret::new(format!(
+ "{}{}{}",
+ self.card_exp_month.peek(),
+ delimiter,
+ year.peek()
+ ))
+ }
+ fn get_expiry_year_4_digit(&self) -> Secret<String> {
+ let mut year = self.card_exp_year.peek().clone();
+ if year.len() == 2 {
+ year = format!("20{}", year);
+ }
+ Secret::new(year)
+ }
+ fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?.expose();
+ let month = self.card_exp_month.clone().expose();
+ Ok(Secret::new(format!("{year}{month}")))
+ }
+ fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
+ self.card_exp_month
+ .peek()
+ .clone()
+ .parse::<i8>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
+ self.card_exp_year
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+}
+
impl CardData for domain::Card {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
@@ -2725,6 +2800,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
match pm_data {
domain::payments::PaymentMethodData::Card(_) => Self::Card,
domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card,
domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => {
match card_redirect_data {
domain::CardRedirectData::Knet {} => Self::Knet,
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index ee34c26d670..c57306efe31 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -210,7 +210,8 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
))?
@@ -1291,7 +1292,8 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
)
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 467a1cba902..dca6f82adc1 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -111,7 +111,8 @@ fn fetch_payment_instrument(
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("worldpay"),
)
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 2b2e7e889e2..799753fd52c 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -697,7 +697,8 @@ impl TryFrom<&ZenRouterData<&types::PaymentsAuthorizeRouterData>> for ZenPayment
| domain::PaymentMethodData::Upi(_)
| domain::PaymentMethodData::OpenBanking(_)
| domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
))?
diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs
index b3e7bfb3bfd..c8758f5322c 100644
--- a/crates/router/src/connector/zsl/transformers.rs
+++ b/crates/router/src/connector/zsl/transformers.rs
@@ -183,6 +183,7 @@ impl TryFrom<&ZslRouterData<&types::PaymentsAuthorizeRouterData>> for ZslPayment
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| domain::PaymentMethodData::OpenBanking(_) => {
Err(errors::ConnectorError::NotImplemented(
connector_utils::get_unimplemented_payment_method_error_message(
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 363d52cd8bf..c81f534857c 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -78,7 +78,9 @@ use crate::{
core::{
errors::{self, CustomResult, RouterResponse, RouterResult},
payment_methods::{cards, network_tokenization},
- payouts, routing as core_routing, utils,
+ payouts,
+ routing::{self as core_routing},
+ utils::{self as core_utils},
},
db::StorageInterface,
logger,
@@ -92,8 +94,8 @@ use crate::{
transformers::{ForeignInto, ForeignTryInto},
},
utils::{
- add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode, OptionExt,
- ValueExt,
+ self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode,
+ OptionExt, ValueExt,
},
workflows::payment_sync,
};
@@ -164,7 +166,7 @@ where
&header_payload,
)
.await?;
- utils::validate_profile_id_from_auth_layer(
+ core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
@@ -649,7 +651,7 @@ where
)
.await?;
- crate::utils::trigger_payments_webhook(
+ utils::trigger_payments_webhook(
merchant_account,
business_profile,
&key_store,
@@ -671,6 +673,206 @@ where
))
}
+// This function is intended for use when the feature being implemented is not aligned with the
+// core payment operations.
+#[allow(clippy::too_many_arguments, clippy::type_complexity)]
+#[instrument(skip_all, fields(payment_id, merchant_id))]
+pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ merchant_account: domain::MerchantAccount,
+ profile_id_from_auth_layer: Option<id_type::ProfileId>,
+ key_store: domain::MerchantKeyStore,
+ operation: Op,
+ req: Req,
+ call_connector_action: CallConnectorAction,
+ auth_flow: services::AuthFlow,
+
+ header_payload: HeaderPayload,
+) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
+where
+ F: Send + Clone + Sync,
+ Req: Authenticate + Clone,
+ Op: Operation<F, Req, Data = D> + Send + Sync,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+
+ // To create connector flow specific interface data
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+
+ // To perform router related operation for PaymentResponse
+ PaymentResponse: Operation<F, FData, Data = D>,
+ FData: Send + Sync + Clone,
+{
+ let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
+
+ tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
+ let (operation, validate_result) = operation
+ .to_validate_request()?
+ .validate_request(&req, &merchant_account)?;
+
+ tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
+
+ let operations::GetTrackerResponse {
+ operation,
+ customer_details: _,
+ mut payment_data,
+ business_profile,
+ mandate_type: _,
+ } = operation
+ .to_get_tracker()?
+ .get_trackers(
+ state,
+ &validate_result.payment_id,
+ &req,
+ &merchant_account,
+ &key_store,
+ auth_flow,
+ &header_payload,
+ )
+ .await?;
+
+ core_utils::validate_profile_id_from_auth_layer(
+ profile_id_from_auth_layer,
+ &payment_data.get_payment_intent().clone(),
+ )?;
+
+ common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || {
+ Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!(
+ "Nti and card details based mit flow is not support for this {operation:?} payment operation"
+ ))
+ })?;
+
+ let connector_choice = operation
+ .to_domain()?
+ .get_connector(
+ &merchant_account,
+ &state.clone(),
+ &req,
+ payment_data.get_payment_intent(),
+ &key_store,
+ )
+ .await?;
+
+ let connector = set_eligible_connector_for_nti_in_payment_data(
+ state,
+ &business_profile,
+ &key_store,
+ &mut payment_data,
+ connector_choice,
+ )
+ .await?;
+
+ let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
+
+ let locale = header_payload.locale.clone();
+
+ let schedule_time = if should_add_task_to_process_tracker {
+ payment_sync::get_sync_process_schedule_time(
+ &*state.store,
+ connector.connector.id(),
+ merchant_account.get_id(),
+ 0,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while getting process schedule time")?
+ } else {
+ None
+ };
+
+ let (router_data, mca) = proxy_for_call_connector_service(
+ state,
+ req_state.clone(),
+ &merchant_account,
+ &key_store,
+ connector.clone(),
+ &operation,
+ &mut payment_data,
+ &None,
+ call_connector_action.clone(),
+ &validate_result,
+ schedule_time,
+ header_payload.clone(),
+ &business_profile,
+ )
+ .await?;
+
+ let op_ref = &operation;
+ let should_trigger_post_processing_flows = is_operation_confirm(&operation);
+
+ let operation = Box::new(PaymentResponse);
+
+ let connector_http_status_code = router_data.connector_http_status_code;
+ let external_latency = router_data.external_latency;
+
+ add_connector_http_status_code_metrics(connector_http_status_code);
+
+ #[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+ let routable_connectors = convert_connector_data_to_routable_connectors(&[connector.clone()])
+ .map_err(|e| logger::error!(routable_connector_error=?e))
+ .unwrap_or_default();
+
+ let mut payment_data = operation
+ .to_post_update_tracker()?
+ .update_tracker(
+ state,
+ &validate_result.payment_id,
+ payment_data,
+ router_data,
+ &key_store,
+ merchant_account.storage_scheme,
+ &locale,
+ #[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+ routable_connectors,
+ #[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+ &business_profile,
+ )
+ .await?;
+
+ if should_trigger_post_processing_flows {
+ complete_postprocessing_steps_if_required(
+ state,
+ &merchant_account,
+ &key_store,
+ &None,
+ &mca,
+ &connector,
+ &mut payment_data,
+ op_ref,
+ Some(header_payload.clone()),
+ )
+ .await?;
+ }
+
+ let cloned_payment_data = payment_data.clone();
+
+ utils::trigger_payments_webhook(
+ merchant_account,
+ business_profile,
+ &key_store,
+ cloned_payment_data,
+ None,
+ state,
+ operation,
+ )
+ .await
+ .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
+ .ok();
+
+ Ok((
+ payment_data,
+ req,
+ None,
+ connector_http_status_code,
+ external_latency,
+ ))
+}
+
#[instrument(skip_all)]
#[cfg(feature = "v1")]
pub async fn call_decision_manager<F, D>(
@@ -977,6 +1179,66 @@ where
)
}
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(
+ state: SessionState,
+ req_state: ReqState,
+ merchant_account: domain::MerchantAccount,
+ profile_id: Option<id_type::ProfileId>,
+ key_store: domain::MerchantKeyStore,
+ operation: Op,
+ req: Req,
+ auth_flow: services::AuthFlow,
+ call_connector_action: CallConnectorAction,
+ header_payload: HeaderPayload,
+) -> RouterResponse<Res>
+where
+ F: Send + Clone + Sync,
+ FData: Send + Sync + Clone,
+ Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
+ Req: Debug + Authenticate + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ Res: transformers::ToResponse<F, D, Op>,
+ // To create connector flow specific interface data
+ D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
+ RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
+
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
+
+ // To perform router related operation for PaymentResponse
+ PaymentResponse: Operation<F, FData, Data = D>,
+{
+ let (payment_data, _req, customer, connector_http_status_code, external_latency) =
+ proxy_for_payments_operation_core::<_, _, _, _, _>(
+ &state,
+ req_state,
+ merchant_account,
+ profile_id,
+ key_store,
+ operation.clone(),
+ req,
+ call_connector_action,
+ auth_flow,
+ header_payload.clone(),
+ )
+ .await?;
+
+ Res::generate_response(
+ payment_data,
+ customer,
+ auth_flow,
+ &state.base_url,
+ operation,
+ &state.conf.connector_request_reference_id_config,
+ connector_http_status_code,
+ external_latency,
+ header_payload.x_hs_latency,
+ )
+}
+
fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
format!("{operation:?}").eq("PaymentStart")
}
@@ -1397,7 +1659,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
)
.await?;
let is_pull_mechanism_enabled =
- crate::utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
+ utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
authentication_merchant_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
@@ -1483,8 +1745,8 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
}?;
// When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client
if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction {
- let req_poll_id = utils::get_external_authentication_request_poll_id(&payment_id);
- let poll_id = utils::get_poll_id(&merchant_id, req_poll_id.clone());
+ let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id);
+ let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone());
let redis_conn = state
.store
.get_redis_conn()
@@ -1551,7 +1813,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
connector.clone(),
)?;
// html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url
- let html = utils::get_html_redirect_response_for_external_authentication(
+ let html = core_utils::get_html_redirect_response_for_external_authentication(
redirect_response.return_url_with_query_params,
payments_response,
payment_id,
@@ -1823,6 +2085,179 @@ where
Ok((router_data, merchant_connector_account))
}
+// This function does not perform the tokenization action, as the payment method is not saved in this flow.
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>(
+ state: &SessionState,
+ req_state: ReqState,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ connector: api::ConnectorData,
+ operation: &BoxedOperation<'_, F, ApiRequest, D>,
+ payment_data: &mut D,
+ customer: &Option<domain::Customer>,
+ call_connector_action: CallConnectorAction,
+ validate_result: &operations::ValidateResult,
+ schedule_time: Option<time::PrimitiveDateTime>,
+ header_payload: HeaderPayload,
+
+ business_profile: &domain::Profile,
+) -> RouterResult<(
+ RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
+ helpers::MerchantConnectorAccountType,
+)>
+where
+ F: Send + Clone + Sync,
+ RouterDReq: Send + Sync,
+
+ // To create connector flow specific interface data
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+ D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
+ RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
+ // To construct connector flow specific api
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
+{
+ let stime_connector = Instant::now();
+
+ let merchant_connector_account = construct_profile_id_and_get_mca(
+ state,
+ merchant_account,
+ payment_data,
+ &connector.connector_name.to_string(),
+ connector.merchant_connector_id.as_ref(),
+ key_store,
+ false,
+ )
+ .await?;
+
+ if payment_data
+ .get_payment_attempt()
+ .merchant_connector_id
+ .is_none()
+ {
+ payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());
+ }
+
+ let merchant_recipient_data = None;
+
+ let mut router_data = payment_data
+ .construct_router_data(
+ state,
+ connector.connector.id(),
+ merchant_account,
+ key_store,
+ customer,
+ &merchant_connector_account,
+ merchant_recipient_data,
+ None,
+ )
+ .await?;
+
+ let add_access_token_result = router_data
+ .add_access_token(
+ state,
+ &connector,
+ merchant_account,
+ payment_data.get_creds_identifier(),
+ )
+ .await?;
+
+ router_data = router_data.add_session_token(state, &connector).await?;
+
+ let mut should_continue_further = access_token::update_router_data_with_access_token_result(
+ &add_access_token_result,
+ &mut router_data,
+ &call_connector_action,
+ );
+
+ (router_data, should_continue_further) = complete_preprocessing_steps_if_required(
+ state,
+ &connector,
+ payment_data,
+ router_data,
+ operation,
+ should_continue_further,
+ )
+ .await?;
+
+ if let Ok(router_types::PaymentsResponseData::PreProcessingResponse {
+ session_token: Some(session_token),
+ ..
+ }) = router_data.response.to_owned()
+ {
+ payment_data.push_sessions_token(session_token);
+ };
+
+ let (connector_request, should_continue_further) = if should_continue_further {
+ // Check if the actual flow specific request can be built with available data
+ router_data
+ .build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
+ .await?
+ } else {
+ (None, false)
+ };
+
+ if should_add_task_to_process_tracker(payment_data) {
+ operation
+ .to_domain()?
+ .add_task_to_process_tracker(
+ state,
+ payment_data.get_payment_attempt(),
+ validate_result.requeue,
+ schedule_time,
+ )
+ .await
+ .map_err(|error| logger::error!(process_tracker_error=?error))
+ .ok();
+ }
+
+ let updated_customer = None;
+ let frm_suggestion = None;
+
+ (_, *payment_data) = operation
+ .to_update_tracker()?
+ .update_trackers(
+ state,
+ req_state,
+ payment_data.clone(),
+ customer.clone(),
+ merchant_account.storage_scheme,
+ updated_customer,
+ key_store,
+ frm_suggestion,
+ header_payload.clone(),
+ )
+ .await?;
+
+ let router_data = if should_continue_further {
+ // The status of payment_attempt and intent will be updated in the previous step
+ // update this in router_data.
+ // This is added because few connector integrations do not update the status,
+ // and rely on previous status set in router_data
+ router_data.status = payment_data.get_payment_attempt().status;
+ router_data
+ .decide_flows(
+ state,
+ &connector,
+ call_connector_action,
+ connector_request,
+ business_profile,
+ header_payload.clone(),
+ )
+ .await
+ } else {
+ Ok(router_data)
+ }?;
+
+ let etime_connector = Instant::now();
+ let duration_connector = etime_connector.saturating_duration_since(stime_connector);
+ tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
+
+ Ok((router_data, merchant_connector_account))
+}
+
pub async fn add_decrypted_payment_method_token<F, D>(
tokenization_action: TokenizationAction,
payment_data: &D,
@@ -2188,7 +2623,7 @@ where
#[cfg(feature = "v1")]
let label = {
- let connector_label = utils::get_connector_label(
+ let connector_label = core_utils::get_connector_label(
payment_data.get_payment_intent().business_country,
payment_data.get_payment_intent().business_label.as_ref(),
payment_data
@@ -3649,6 +4084,120 @@ where
Ok(connector)
}
+async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &D,
+ connector_choice: T,
+
+ business_profile: &domain::Profile,
+) -> RouterResult<(
+ api_models::payments::MandateReferenceId,
+ hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
+ api::ConnectorData,
+)>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ // Since this flow will only be used in the MIT flow, recurring details are mandatory.
+ let recurring_payment_details = payment_data
+ .get_recurring_details()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("Failed to fetch recurring details for mit")?;
+
+ let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?;
+
+ let network_transaction_id_supported_connectors = &state
+ .conf
+ .network_transaction_id_supported_connectors
+ .connector_list
+ .iter()
+ .map(|value| value.to_string())
+ .collect::<HashSet<_>>();
+
+ let eligible_connector_data_list = connector_choice
+ .get_routable_connectors(&*state.store, business_profile)
+ .await?
+ .filter_network_transaction_id_flow_supported_connectors(
+ network_transaction_id_supported_connectors.to_owned(),
+ )
+ .construct_dsl_and_perform_eligibility_analysis(
+ state,
+ key_store,
+ payment_data,
+ business_profile.get_id(),
+ )
+ .await
+ .attach_printable("Failed to fetch eligible connector data")?;
+
+ let eligible_connector_data = eligible_connector_data_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable(
+ "No eligible connector found for the network transaction id based mit flow",
+ )?;
+ Ok((
+ mandate_reference_id,
+ card_details_for_network_transaction_id,
+ eligible_connector_data.clone(),
+ ))
+}
+
+pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>(
+ state: &SessionState,
+ business_profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut D,
+ connector_choice: api::ConnectorChoice,
+) -> RouterResult<api::ConnectorData>
+where
+ F: Send + Clone,
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) =
+ match connector_choice {
+ api::ConnectorChoice::StraightThrough(straight_through) => {
+ get_eligible_connector_for_nti(
+ state,
+ key_store,
+ payment_data,
+ core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
+ business_profile,
+ )
+ .await?
+ }
+ api::ConnectorChoice::Decide => {
+ get_eligible_connector_for_nti(
+ state,
+ key_store,
+ payment_data,
+ core_routing::DecideConnector,
+ business_profile,
+ )
+ .await?
+ }
+ api::ConnectorChoice::SessionMultiple(_) => {
+ Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
+ "Invalid routing rule configured for nti and card details based mit flow",
+ )?
+ }
+ };
+
+ // Set `NetworkMandateId` as the MandateId
+ payment_data.set_mandate_id(payments_api::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(mandate_reference_id),
+ });
+
+ // Set the card details received in the recurring details within the payment method data.
+ payment_data.set_payment_method_data(Some(
+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id),
+ ));
+
+ Ok(eligible_connector_data)
+}
+
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn connector_selection<F, D>(
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a39b151bd27..88730b3b0f6 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -434,6 +434,9 @@ pub async fn get_token_pm_type_mandate_details(
match &request.recurring_details {
Some(recurring_details) => {
match recurring_details {
+ RecurringDetails::NetworkTransactionIdAndCardDetails(_) => {
+ (None, request.payment_method, None, None, None, None, None)
+ }
RecurringDetails::ProcessorPaymentToken(processor_payment_token) => {
if let Some(mca_id) = &processor_payment_token.merchant_connector_id {
let db = &*state.store;
@@ -1227,7 +1230,8 @@ fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult
.get_required_value("recurring_details")?;
match recurring_details {
- RecurringDetails::ProcessorPaymentToken(_) => Ok(()),
+ RecurringDetails::ProcessorPaymentToken(_)
+ | RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
@@ -1821,16 +1825,60 @@ pub async fn retrieve_card_with_permanent_token(
})?;
if !business_profile.is_network_tokenization_enabled {
- fetch_card_details_from_locker(
- state,
- customer_id,
- &payment_intent.merchant_id,
- locker_id,
- card_token_data,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to fetch card information from the permanent locker")
+ let is_network_transaction_id_flow = mandate_id
+ .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow())
+ .unwrap_or(false);
+
+ if is_network_transaction_id_flow {
+ let card_details_from_locker = cards::get_card_from_locker(
+ state,
+ customer_id,
+ &payment_intent.merchant_id,
+ locker_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch card details from locker")?;
+
+ let card_network = card_details_from_locker
+ .card_brand
+ .map(|card_brand| enums::CardNetwork::from_str(&card_brand))
+ .transpose()
+ .map_err(|e| {
+ logger::error!("Failed to parse card network {e:?}");
+ })
+ .ok()
+ .flatten();
+
+ let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId {
+ card_number: card_details_from_locker.card_number,
+ card_exp_month: card_details_from_locker.card_exp_month,
+ card_exp_year: card_details_from_locker.card_exp_year,
+ card_issuer: None,
+ card_network,
+ card_type: None,
+ card_issuing_country: None,
+ bank_code: None,
+ nick_name: card_details_from_locker.nick_name.map(masking::Secret::new),
+ };
+
+ Ok(
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(
+ card_details_for_network_transaction_id,
+ ),
+ )
+ } else {
+ fetch_card_details_from_locker(
+ state,
+ customer_id,
+ &payment_intent.merchant_id,
+ locker_id,
+ card_token_data,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch card information from the permanent locker")
+ }
} else {
match (payment_method_info, mandate_id) {
(None, _) => Err(errors::ApiErrorResponse::InternalServerError)
@@ -1927,17 +1975,42 @@ pub async fn retrieve_card_with_permanent_token(
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
- fetch_card_details_from_locker(
+ let card_details_from_locker = cards::get_card_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
- card_token_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "failed to fetch card information from the permanent locker",
+ .attach_printable("failed to fetch card details from locker")?;
+
+ let card_network = card_details_from_locker
+ .card_brand
+ .map(|card_brand| enums::CardNetwork::from_str(&card_brand))
+ .transpose()
+ .map_err(|e| {
+ logger::error!("Failed to parse card network {e:?}");
+ })
+ .ok()
+ .flatten();
+
+ let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId {
+ card_number: card_details_from_locker.card_number,
+ card_exp_month: card_details_from_locker.card_exp_month,
+ card_exp_year: card_details_from_locker.card_exp_year,
+ card_issuer: None,
+ card_network,
+ card_type: None,
+ card_issuing_country: None,
+ bank_code: None,
+ nick_name: card_details_from_locker.nick_name.map(masking::Secret::new),
+ };
+
+ Ok(
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(
+ card_details_for_network_transaction_id,
+ ),
)
}
@@ -4418,6 +4491,110 @@ pub async fn get_additional_payment_data(
details: Some(open_banking.to_owned().into()),
},
)),
+ domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => {
+ let card_isin = Some(card_data.card_number.get_card_isin());
+ let enable_extended_bin =db
+ .find_config_by_key_unwrap_or(
+ format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
+ Some("false".to_string()))
+ .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
+
+ let card_extended_bin = match enable_extended_bin {
+ Some(config) if config.config == "true" => {
+ Some(card_data.card_number.get_extended_card_bin())
+ }
+ _ => None,
+ };
+
+ let card_network = match card_data
+ .card_number
+ .is_cobadged_card()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Card cobadge check failed due to an invalid card network regex",
+ )? {
+ true => card_data.card_network.clone(),
+ false => None,
+ };
+
+ let last4 = Some(card_data.card_number.get_last4());
+ if card_data.card_issuer.is_some()
+ && card_network.is_some()
+ && card_data.card_type.is_some()
+ && card_data.card_issuing_country.is_some()
+ && card_data.bank_code.is_some()
+ {
+ Ok(Some(api_models::payments::AdditionalPaymentData::Card(
+ Box::new(api_models::payments::AdditionalCardInfo {
+ card_issuer: card_data.card_issuer.to_owned(),
+ card_network,
+ card_type: card_data.card_type.to_owned(),
+ card_issuing_country: card_data.card_issuing_country.to_owned(),
+ bank_code: card_data.bank_code.to_owned(),
+ card_exp_month: Some(card_data.card_exp_month.clone()),
+ card_exp_year: Some(card_data.card_exp_year.clone()),
+ card_holder_name: card_data.nick_name.clone(), //todo!
+ last4: last4.clone(),
+ card_isin: card_isin.clone(),
+ card_extended_bin: card_extended_bin.clone(),
+ // These are filled after calling the processor / connector
+ payment_checks: None,
+ authentication_data: None,
+ }),
+ )))
+ } else {
+ let card_info = card_isin
+ .clone()
+ .async_and_then(|card_isin| async move {
+ db.get_card_info(&card_isin)
+ .await
+ .map_err(|error| services::logger::warn!(card_info_error=?error))
+ .ok()
+ })
+ .await
+ .flatten()
+ .map(|card_info| {
+ api_models::payments::AdditionalPaymentData::Card(Box::new(
+ api_models::payments::AdditionalCardInfo {
+ card_issuer: card_info.card_issuer,
+ card_network,
+ bank_code: card_info.bank_code,
+ card_type: card_info.card_type,
+ card_issuing_country: card_info.card_issuing_country,
+ last4: last4.clone(),
+ card_isin: card_isin.clone(),
+ card_extended_bin: card_extended_bin.clone(),
+ card_exp_month: Some(card_data.card_exp_month.clone()),
+ card_exp_year: Some(card_data.card_exp_year.clone()),
+ card_holder_name: card_data.nick_name.clone(), //todo!
+ // These are filled after calling the processor / connector
+ payment_checks: None,
+ authentication_data: None,
+ },
+ ))
+ });
+ Ok(Some(card_info.unwrap_or_else(|| {
+ api_models::payments::AdditionalPaymentData::Card(Box::new(
+ api_models::payments::AdditionalCardInfo {
+ card_issuer: None,
+ card_network: None,
+ bank_code: None,
+ card_type: None,
+ card_issuing_country: None,
+ last4,
+ card_isin,
+ card_extended_bin,
+ card_exp_month: Some(card_data.card_exp_month.clone()),
+ card_exp_year: Some(card_data.card_exp_year.clone()),
+ card_holder_name: card_data.nick_name.clone(), //todo!
+ // These are filled after calling the processor / connector
+ payment_checks: None,
+ authentication_data: None,
+ },
+ ))
+ })))
+ }
+ }
domain::PaymentMethodData::NetworkToken(_) => Ok(None),
}
}
@@ -5131,8 +5308,9 @@ pub fn get_key_params_for_surcharge_details(
ob_data.get_payment_method_type(),
None,
)),
- domain::PaymentMethodData::CardToken(_) => None,
- domain::PaymentMethodData::NetworkToken(_) => None,
+ domain::PaymentMethodData::CardToken(_)
+ | domain::PaymentMethodData::NetworkToken(_)
+ | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6a5299db8c4..d5c3fa3c4ae 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1090,6 +1090,9 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => {
payment_data.payment_attempt.payment_method_data.clone()
}
+ hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ payment_data.payment_attempt.payment_method_data.clone()
+ }
},
None => None,
};
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 04080a42730..a8423faada1 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -400,6 +400,20 @@ pub fn perform_straight_through_routing(
})
}
+pub fn perform_routing_for_single_straight_through_algorithm(
+ algorithm: &routing_types::StraightThroughAlgorithm,
+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
+ Ok(match algorithm {
+ routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()],
+
+ routing_types::StraightThroughAlgorithm::Priority(_)
+ | routing_types::StraightThroughAlgorithm::VolumeSplit(_) => {
+ Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
+ .attach_printable("Unsupported algorithm received as a result of static routing")?
+ }
+ })
+}
+
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
@@ -646,7 +660,7 @@ pub async fn refresh_cgraph_cache<'a>(
}
#[allow(clippy::too_many_arguments)]
-async fn perform_cgraph_filtering(
+pub async fn perform_cgraph_filtering(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index b7b1c13ea80..926b30081bf 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -1,10 +1,12 @@
pub mod helpers;
pub mod transformers;
+use std::collections::HashSet;
use api_models::{
enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
};
+use async_trait::async_trait;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
use hyperswitch_domain_models::{mandates, payment_address};
@@ -17,22 +19,27 @@ use storage_impl::redis::cache;
#[cfg(feature = "payouts")]
use super::payouts;
+use super::{
+ errors::RouterResult,
+ payments::{
+ routing::{self as payments_routing},
+ OperationSessionGetters,
+ },
+};
#[cfg(feature = "v1")]
use crate::utils::ValueExt;
#[cfg(feature = "v2")]
-use crate::{
- core::{admin, errors::RouterResult},
- db::StorageInterface,
-};
+use crate::{core::admin, utils::ValueExt};
use crate::{
core::{
- errors::{self, RouterResponse, StorageErrorExt},
+ errors::{self, CustomResult, RouterResponse, StorageErrorExt},
metrics, utils as core_utils,
},
+ db::StorageInterface,
routes::SessionState,
services::api as service_api,
types::{
- domain,
+ api, domain,
storage::{self, enums as storage_enums},
transformers::{ForeignInto, ForeignTryFrom},
},
@@ -1383,3 +1390,141 @@ pub async fn success_based_routing_update_configs(
);
Ok(service_api::ApplicationResponse::Json(new_record))
}
+
+#[async_trait]
+pub trait GetRoutableConnectorsForChoice {
+ async fn get_routable_connectors(
+ &self,
+ db: &dyn StorageInterface,
+ business_profile: &domain::Profile,
+ ) -> RouterResult<RoutableConnectors>;
+}
+
+pub struct StraightThroughAlgorithmTypeSingle(pub serde_json::Value);
+
+#[async_trait]
+impl GetRoutableConnectorsForChoice for StraightThroughAlgorithmTypeSingle {
+ async fn get_routable_connectors(
+ &self,
+ _db: &dyn StorageInterface,
+ _business_profile: &domain::Profile,
+ ) -> RouterResult<RoutableConnectors> {
+ let straight_through_routing_algorithm = self
+ .0
+ .clone()
+ .parse_value::<api::routing::StraightThroughAlgorithm>("RoutingAlgorithm")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse the straight through routing algorithm")?;
+ let routable_connector = match straight_through_routing_algorithm {
+ api::routing::StraightThroughAlgorithm::Single(connector) => {
+ vec![*connector]
+ }
+
+ api::routing::StraightThroughAlgorithm::Priority(_)
+ | api::routing::StraightThroughAlgorithm::VolumeSplit(_) => {
+ Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Unsupported algorithm received as a result of static routing",
+ )?
+ }
+ };
+ Ok(RoutableConnectors(routable_connector))
+ }
+}
+
+pub struct DecideConnector;
+
+#[async_trait]
+impl GetRoutableConnectorsForChoice for DecideConnector {
+ async fn get_routable_connectors(
+ &self,
+ db: &dyn StorageInterface,
+ business_profile: &domain::Profile,
+ ) -> RouterResult<RoutableConnectors> {
+ let fallback_config = helpers::get_merchant_default_config(
+ db,
+ business_profile.get_id().get_string_repr(),
+ &common_enums::TransactionType::Payment,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ Ok(RoutableConnectors(fallback_config))
+ }
+}
+
+pub struct RoutableConnectors(Vec<routing_types::RoutableConnectorChoice>);
+
+impl RoutableConnectors {
+ pub fn filter_network_transaction_id_flow_supported_connectors(
+ self,
+ nit_connectors: HashSet<String>,
+ ) -> Self {
+ let connectors = self
+ .0
+ .into_iter()
+ .filter(|routable_connector_choice| {
+ nit_connectors.contains(&routable_connector_choice.connector.to_string())
+ })
+ .collect();
+ Self(connectors)
+ }
+
+ pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>(
+ self,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &D,
+
+ profile_id: &common_utils::id_type::ProfileId,
+ ) -> RouterResult<Vec<api::ConnectorData>>
+ where
+ F: Send + Clone,
+ D: OperationSessionGetters<F>,
+ {
+ let payments_dsl_input = PaymentsDslInput::new(
+ payment_data.get_setup_mandate(),
+ payment_data.get_payment_attempt(),
+ payment_data.get_payment_intent(),
+ payment_data.get_payment_method_data(),
+ payment_data.get_address(),
+ payment_data.get_recurring_details(),
+ payment_data.get_currency(),
+ );
+
+ let routable_connector_choice = self.0.clone();
+
+ let backend_input = payments_routing::make_dsl_input(&payments_dsl_input)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to construct dsl input")?;
+
+ let connectors = payments_routing::perform_cgraph_filtering(
+ state,
+ key_store,
+ routable_connector_choice,
+ backend_input,
+ None,
+ profile_id,
+ &common_enums::TransactionType::Payment,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Eligibility analysis failed for routable connectors")?;
+
+ let connector_data = connectors
+ .into_iter()
+ .map(|conn| {
+ api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &conn.connector.to_string(),
+ api::GetToken::Connector,
+ conn.merchant_connector_id.clone(),
+ )
+ })
+ .collect::<CustomResult<Vec<_>, _>>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Invalid connector name received")?;
+
+ Ok(connector_data)
+ }
+}
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 5e0c19e3da9..3972adeb116 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1258,55 +1258,87 @@ where
// the operation are flow agnostic, and the flow is only required in the post_update_tracker
// Thus the flow can be generated just before calling the connector instead of explicitly passing it here.
- let eligible_connectors = req.connector.clone();
- 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,
- _,
- _,
- _,
- payments::PaymentData<api_types::Authorize>,
- >(
- state,
- req_state,
- merchant_account,
- profile_id,
- key_store,
- operation,
- req,
- auth_flow,
- payments::CallConnectorAction::Trigger,
- eligible_connectors,
- header_payload,
- )
- .await
- }
- api_models::enums::PaymentType::SetupMandate => {
- payments::payments_core::<
- api_types::SetupMandate,
- payment_types::PaymentsResponse,
- _,
- _,
- _,
- payments::PaymentData<api_types::SetupMandate>,
- >(
- state,
- req_state,
- merchant_account,
- profile_id,
- key_store,
- operation,
- req,
- auth_flow,
- payments::CallConnectorAction::Trigger,
- eligible_connectors,
- header_payload,
- )
- .await
+ let is_recurring_details_type_nti_and_card_details = req
+ .recurring_details
+ .clone()
+ .map(|recurring_details| {
+ recurring_details.is_network_transaction_id_and_card_details_flow()
+ })
+ .unwrap_or(false);
+ if is_recurring_details_type_nti_and_card_details {
+ // no list of eligible connectors will be passed in the confirm call
+ logger::debug!("Authorize call for NTI and Card Details flow");
+ payments::proxy_for_payments_core::<
+ api_types::Authorize,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ payments::PaymentData<api_types::Authorize>,
+ >(
+ state,
+ req_state,
+ merchant_account,
+ profile_id,
+ key_store,
+ operation,
+ req,
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ header_payload,
+ )
+ .await
+ } else {
+ let eligible_connectors = req.connector.clone();
+ 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,
+ _,
+ _,
+ _,
+ payments::PaymentData<api_types::Authorize>,
+ >(
+ state,
+ req_state,
+ merchant_account,
+ profile_id,
+ key_store,
+ operation,
+ req,
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ eligible_connectors,
+ header_payload,
+ )
+ .await
+ }
+ api_models::enums::PaymentType::SetupMandate => {
+ payments::payments_core::<
+ api_types::SetupMandate,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ payments::PaymentData<api_types::SetupMandate>,
+ >(
+ state,
+ req_state,
+ merchant_account,
+ profile_id,
+ key_store,
+ operation,
+ req,
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ eligible_connectors,
+ header_payload,
+ )
+ .await
+ }
}
}
}
| 2024-10-07T04:35:39Z |
## Description
<!-- Describe your changes in detail -->
Support needs to be added in order to accept the card details and network transaction id in `recurring_details` for an MIT. This will be only in the Sever-to-Server call where the customer is off_session and merchant is initiating the transaction who is a PCI entity and has stored his customer card details and network transaction id.
Support needs to be added to accept card details and the network transaction ID in `recurring_details` for a Merchant Initiated Transaction (MIT). This will only apply to the Server-to-Server call, where the customer is off-session, and the merchant, as a PCI entity, initiates the transaction using stored customer card details and the network transaction ID.
As in this case we are not creating customer or any payment method entries in hyperswitch we have separate `proxy_for_payments_operation_core` to decouple this flow from the actual payments flow.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create the cybersource connector
-> Make a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"customer": {
"id": "cu_1728547396",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_LJtnKnvXs8jKvnKuXMIX",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_LJtnKnvXs8jKvnKuXMIX_secret_FEM1cSMicyLY98zCFteH",
"created": "2024-10-10T08:03:13.122Z",
"currency": "USD",
"customer_id": "cu_1728547393",
"customer": {
"id": "cu_1728547393",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "INTL HDQTRS-CENTER OWNED",
"card_issuing_country": "UNITEDSTATES",
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QroHqbvm2W37jpJ2F3Dm",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547393",
"created_at": 1728547393,
"expires": 1728550993,
"secret": "epk_77cc29d490214a0782d6f50b05451576"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285473978946309103955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_LJtnKnvXs8jKvnKuXMIX_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:18:13.122Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:03:18.498Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> make an off_session payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1728547463",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}'
```
```
{
"payment_id": "pay_FldSIzn6XLw6GFlo4jgv",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_FldSIzn6XLw6GFlo4jgv_secret_2vnIsPxnnDtw0fBkjk1h",
"created": "2024-10-10T08:04:16.308Z",
"currency": "USD",
"customer_id": "cu_1728547456",
"customer": {
"id": "cu_1728547456",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_Krvco9uW970Wfgkh17k5",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547456",
"created_at": 1728547456,
"expires": 1728551056,
"secret": "epk_789e4d9885f641eebdf614a13aca5ce7"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285474566096322903955",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_FldSIzn6XLw6GFlo4jgv_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:19:16.308Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_8XMshMDnMmX0kTJdW8nN",
"payment_method_status": null,
"updated": "2024-10-10T08:04:17.464Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Recurring payment with `payment_method_id`
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"customer_id": "cu_1728547456",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_8XMshMDnMmX0kTJdW8nN"
},
"routing": {
"type": "single",
"data": {
"connector": "cybersource",
"merchant_connector_id": "mca_Du9p7M4scSePxCvcT0sB"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_ztOyuYK1URN4ZjrmoVFG",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_ztOyuYK1URN4ZjrmoVFG_secret_MKkEQBQ39hyV8Glvn6ys",
"created": "2024-10-10T08:06:17.284Z",
"currency": "USD",
"customer_id": "cu_1728547456",
"customer": {
"id": "cu_1728547456",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547456",
"created_at": 1728547577,
"expires": 1728551177,
"secret": "epk_b997deec53b847a4a1604344d3c34a71"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285475783556350603955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_ztOyuYK1URN4ZjrmoVFG_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:21:17.284Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_8XMshMDnMmX0kTJdW8nN",
"payment_method_status": "active",
"updated": "2024-10-10T08:06:19.048Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": "241BC28127133EFFE063AF598E0A1D8A"
}
```
-> Create payment with recurring details `"type": "network_transaction_id_and_card_details"`
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"off_session": true,
"recurring_details": {
"type": "network_transaction_id_and_card_details",
"data": {
"card_number": "5454545454545454",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"network_transaction_id": "737"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_wm0BK9Bja4vD9JGmo2dS",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": null,
"client_secret": "pay_wm0BK9Bja4vD9JGmo2dS_secret_ScT0wh8z52QQoeBiDKqz",
"created": "2024-10-10T08:08:24.405Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "5454",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.",
"card_issuing_country": "POLAND",
"card_isin": "545454",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7285477054756884503954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_wm0BK9Bja4vD9JGmo2dS_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:23:24.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:08:26.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Retrieve the payment
```
curl --location 'http://localhost:8080/payments/pay_wm0BK9Bja4vD9JGmo2dS' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs'
```
```
{
"payment_id": "pay_wm0BK9Bja4vD9JGmo2dS",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": null,
"client_secret": "pay_wm0BK9Bja4vD9JGmo2dS_secret_ScT0wh8z52QQoeBiDKqz",
"created": "2024-10-10T08:08:24.405Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "5454",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.",
"card_issuing_country": "POLAND",
"card_isin": "545454",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7285477054756884503954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_wm0BK9Bja4vD9JGmo2dS_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:23:24.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:08:26.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Test PG_agnostic mandates
-> Create a connector and enable `is_connector_agnostic_mit_enabled`
```
curl --location 'http://localhost:8080/account/merchant_1728548411/business_profile/pro_YarikMeqoVUIawALRJS7' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"is_connector_agnostic_mit_enabled": true
}'
```
-> Create a off_session payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_Hy7bgv6IGxvVGfWAtdSIuZolXWpCcXwDZsvBm4qGB3SjwYIOE3KbNZh4aPpkifsz' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1728554157",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}'
```
```
{
"payment_id": "pay_krHDNyFZpvRwM3R28PC6",
"merchant_id": "merchant_1728548411",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_krHDNyFZpvRwM3R28PC6_secret_n3KXhz6TKmDAMyVm2okC",
"created": "2024-10-10T08:23:17.564Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_Funtb7OO6L5wRhd7DsaY",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728548597",
"created_at": 1728548597,
"expires": 1728552197,
"secret": "epk_19f37752f10d44e89e55d60bc9a94e03"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285485985906199003954",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_krHDNyFZpvRwM3R28PC6_1",
"payment_link": null,
"profile_id": "pro_YarikMeqoVUIawALRJS7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_4St9u5v9GZvl7FoAwEiU",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:38:17.564Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_N6t0gBJt1ktj4tef5mCT",
"payment_method_status": null,
"updated": "2024-10-10T08:23:19.342Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Using the above payment method id make a recurring payment with other connector
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_Hy7bgv6IGxvVGfWAtdSIuZolXWpCcXwDZsvBm4qGB3SjwYIOE3KbNZh4aPpkifsz' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"off_session": true,
"customer_id": "cu_1728548597",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_N6t0gBJt1ktj4tef5mCT"
},
"routing": {
"type": "single",
"data": {
"connector": "stripe",
"merchant_connector_id": "mca_kMKyXTBRlW8K3Ywzi2mT"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_JzDuaak6BLm00of1QK3a",
"merchant_id": "merchant_1728548411",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "stripe",
"client_secret": "pay_JzDuaak6BLm00of1QK3a_secret_nGLRTZD7785H9Xbuz2gN",
"created": "2024-10-10T09:50:24.069Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728548597",
"created_at": 1728553824,
"expires": 1728557424,
"secret": "epk_f703b591d98b42d095e7bf2da08b3b6e"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3Q8J0mEOqOywnAIx1Ud59gRb",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3Q8J0mEOqOywnAIx1Ud59gRb",
"payment_link": null,
"profile_id": "pro_YarikMeqoVUIawALRJS7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_kMKyXTBRlW8K3Ywzi2mT",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T10:05:24.069Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_N6t0gBJt1ktj4tef5mCT",
"payment_method_status": "active",
"updated": "2024-10-10T09:50:25.782Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Ran cybersource test cases locally. There are some know test case that have failed.
<img width="727" alt="image" src="https://github.com/user-attachments/assets/e3fb2e14-e2cf-4498-aa96-3e762712ba6a"> | e911ea4615294d136210bcf9a8bd4b3ab39ca85f |
-> Create the cybersource connector
-> Make a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--data-raw '{
"amount": 100,
"amount_to_capture": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"customer": {
"id": "cu_1728547396",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "http://127.0.0.1:4040",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000119",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
```
{
"payment_id": "pay_LJtnKnvXs8jKvnKuXMIX",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_LJtnKnvXs8jKvnKuXMIX_secret_FEM1cSMicyLY98zCFteH",
"created": "2024-10-10T08:03:13.122Z",
"currency": "USD",
"customer_id": "cu_1728547393",
"customer": {
"id": "cu_1728547393",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0119",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "INTL HDQTRS-CENTER OWNED",
"card_issuing_country": "UNITEDSTATES",
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_QroHqbvm2W37jpJ2F3Dm",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "http://127.0.0.1:4040/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547393",
"created_at": 1728547393,
"expires": 1728550993,
"secret": "epk_77cc29d490214a0782d6f50b05451576"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285473978946309103955",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_LJtnKnvXs8jKvnKuXMIX_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:18:13.122Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:03:18.498Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> make an off_session payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1728547463",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}'
```
```
{
"payment_id": "pay_FldSIzn6XLw6GFlo4jgv",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_FldSIzn6XLw6GFlo4jgv_secret_2vnIsPxnnDtw0fBkjk1h",
"created": "2024-10-10T08:04:16.308Z",
"currency": "USD",
"customer_id": "cu_1728547456",
"customer": {
"id": "cu_1728547456",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_Krvco9uW970Wfgkh17k5",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547456",
"created_at": 1728547456,
"expires": 1728551056,
"secret": "epk_789e4d9885f641eebdf614a13aca5ce7"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285474566096322903955",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_FldSIzn6XLw6GFlo4jgv_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:19:16.308Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_8XMshMDnMmX0kTJdW8nN",
"payment_method_status": null,
"updated": "2024-10-10T08:04:17.464Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Recurring payment with `payment_method_id`
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"customer_id": "cu_1728547456",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_8XMshMDnMmX0kTJdW8nN"
},
"routing": {
"type": "single",
"data": {
"connector": "cybersource",
"merchant_connector_id": "mca_Du9p7M4scSePxCvcT0sB"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_ztOyuYK1URN4ZjrmoVFG",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_ztOyuYK1URN4ZjrmoVFG_secret_MKkEQBQ39hyV8Glvn6ys",
"created": "2024-10-10T08:06:17.284Z",
"currency": "USD",
"customer_id": "cu_1728547456",
"customer": {
"id": "cu_1728547456",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728547456",
"created_at": 1728547577,
"expires": 1728551177,
"secret": "epk_b997deec53b847a4a1604344d3c34a71"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285475783556350603955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_ztOyuYK1URN4ZjrmoVFG_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:21:17.284Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_8XMshMDnMmX0kTJdW8nN",
"payment_method_status": "active",
"updated": "2024-10-10T08:06:19.048Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": "241BC28127133EFFE063AF598E0A1D8A"
}
```
-> Create payment with recurring details `"type": "network_transaction_id_and_card_details"`
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"off_session": true,
"recurring_details": {
"type": "network_transaction_id_and_card_details",
"data": {
"card_number": "5454545454545454",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"network_transaction_id": "737"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_wm0BK9Bja4vD9JGmo2dS",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": null,
"client_secret": "pay_wm0BK9Bja4vD9JGmo2dS_secret_ScT0wh8z52QQoeBiDKqz",
"created": "2024-10-10T08:08:24.405Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "5454",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.",
"card_issuing_country": "POLAND",
"card_isin": "545454",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7285477054756884503954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_wm0BK9Bja4vD9JGmo2dS_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:23:24.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:08:26.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Retrieve the payment
```
curl --location 'http://localhost:8080/payments/pay_wm0BK9Bja4vD9JGmo2dS' \
--header 'Accept: application/json' \
--header 'api-key: dev_tsD2yHJdXXW6s9EMzxgsDgJiJbQEzCLt0l0ysqlOc0tV9F1CACTCTWdHOdtJcoYs'
```
```
{
"payment_id": "pay_wm0BK9Bja4vD9JGmo2dS",
"merchant_id": "merchant_1728547347",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": null,
"client_secret": "pay_wm0BK9Bja4vD9JGmo2dS_secret_ScT0wh8z52QQoeBiDKqz",
"created": "2024-10-10T08:08:24.405Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "5454",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "BANKHANDLOWYWWARSZAWIE.S.A.",
"card_issuing_country": "POLAND",
"card_isin": "545454",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7285477054756884503954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_wm0BK9Bja4vD9JGmo2dS_1",
"payment_link": null,
"profile_id": "pro_VVvrfmL3csO2vjvGjf3E",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ahtWpAsQ9RYW7eyEOZs4",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:23:24.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-10T08:08:26.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Test PG_agnostic mandates
-> Create a connector and enable `is_connector_agnostic_mit_enabled`
```
curl --location 'http://localhost:8080/account/merchant_1728548411/business_profile/pro_YarikMeqoVUIawALRJS7' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"is_connector_agnostic_mit_enabled": true
}'
```
-> Create a off_session payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_Hy7bgv6IGxvVGfWAtdSIuZolXWpCcXwDZsvBm4qGB3SjwYIOE3KbNZh4aPpkifsz' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 100,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "cu_1728554157",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "name name",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "ss"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}'
```
```
{
"payment_id": "pay_krHDNyFZpvRwM3R28PC6",
"merchant_id": "merchant_1728548411",
"status": "succeeded",
"amount": 100,
"net_amount": 100,
"amount_capturable": 0,
"amount_received": 100,
"connector": "cybersource",
"client_secret": "pay_krHDNyFZpvRwM3R28PC6_secret_n3KXhz6TKmDAMyVm2okC",
"created": "2024-10-10T08:23:17.564Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_Funtb7OO6L5wRhd7DsaY",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": "ss"
},
"phone": null,
"email": null
},
"order_details": [
{
"brand": null,
"amount": 0,
"category": null,
"quantity": 1,
"product_id": null,
"product_name": "Apple iphone 15",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"requires_shipping": null
}
],
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728548597",
"created_at": 1728548597,
"expires": 1728552197,
"secret": "epk_19f37752f10d44e89e55d60bc9a94e03"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7285485985906199003954",
"frm_message": null,
"metadata": {},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_krHDNyFZpvRwM3R28PC6_1",
"payment_link": null,
"profile_id": "pro_YarikMeqoVUIawALRJS7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_4St9u5v9GZvl7FoAwEiU",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T08:38:17.564Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "125.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_N6t0gBJt1ktj4tef5mCT",
"payment_method_status": null,
"updated": "2024-10-10T08:23:19.342Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Using the above payment method id make a recurring payment with other connector
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_Hy7bgv6IGxvVGfWAtdSIuZolXWpCcXwDZsvBm4qGB3SjwYIOE3KbNZh4aPpkifsz' \
--header 'Content-Type: application/json' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"email": "guest@example.com",
"payment_method": "card",
"payment_method_type": "credit",
"off_session": true,
"customer_id": "cu_1728548597",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_N6t0gBJt1ktj4tef5mCT"
},
"routing": {
"type": "single",
"data": {
"connector": "stripe",
"merchant_connector_id": "mca_kMKyXTBRlW8K3Ywzi2mT"
}
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
}
}'
```
```
{
"payment_id": "pay_JzDuaak6BLm00of1QK3a",
"merchant_id": "merchant_1728548411",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "stripe",
"client_secret": "pay_JzDuaak6BLm00of1QK3a_secret_nGLRTZD7785H9Xbuz2gN",
"created": "2024-10-10T09:50:24.069Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": null,
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1728548597",
"created_at": 1728553824,
"expires": 1728557424,
"secret": "epk_f703b591d98b42d095e7bf2da08b3b6e"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3Q8J0mEOqOywnAIx1Ud59gRb",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3Q8J0mEOqOywnAIx1Ud59gRb",
"payment_link": null,
"profile_id": "pro_YarikMeqoVUIawALRJS7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_kMKyXTBRlW8K3Ywzi2mT",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-10T10:05:24.069Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_N6t0gBJt1ktj4tef5mCT",
"payment_method_status": "active",
"updated": "2024-10-10T09:50:25.782Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Ran cybersource test cases locally. There are some know test case that have failed.
<img width="727" alt="image" src="https://github.com/user-attachments/assets/e3fb2e14-e2cf-4498-aa96-3e762712ba6a">
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/mandates.rs",
"crates/api_models/src/payments.rs",
"crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs",
"crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs",
"crates/hyperswitch_connectors/src/connectors/dl... | |
juspay/hyperswitch | juspay__hyperswitch-6242 | Bug: [BUG] Broken links to Running additional services
### Bug Description
These lines:
- https://github.com/juspay/hyperswitch/blob/b7139483bb4735b7dfaf7e659ab33a16a90af1db/README.md?plain=1#L137,
- https://github.com/juspay/hyperswitch/blob/b7139483bb4735b7dfaf7e659ab33a16a90af1db/docs/try_local_system.md?plain=1#L59,
- https://github.com/juspay/hyperswitch/blob/b7139483bb4735b7dfaf7e659ab33a16a90af1db/docs/try_local_system.md?plain=1#L157,
Contain links to non existing section.
### Expected Behavior
I should be taken to the intended part of the documentation.
### Actual Behavior
Takes me to the top of the `try_local_system.md` page.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to mentioned the lines mentioned above
2. Click on the link
### Context For The Bug
The proper target should be this:
https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#running-additional-services
### Environment
Not relevant.
### 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/README.md b/README.md
index 0428ff38694..f5c27411b51 100644
--- a/README.md
+++ b/README.md
@@ -134,7 +134,7 @@ setup, which includes the [scheduler and monitoring services][docker-compose-sch
[website-link]: https://hyperswitch.io/
[learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows
[local-setup-guide]: /docs/try_local_system.md
-[docker-compose-scheduler-monitoring]: /docs/try_local_system.md#run-the-scheduler-and-monitoring-services
+[docker-compose-scheduler-monitoring]: /docs/try_local_system.md#running-additional-services
<a href="#Fast-Integration-for-Stripe-Users">
<h2 id="fast-integration-for-stripe-users">🔌 Fast Integration for Stripe Users</h2>
</a>
| 2024-10-06T11:24:54Z |
## Description
<!-- Describe your changes in detail -->
Changed the links to point to:
https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md#running-additional-services
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6242.
## How did you test 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 checked the links. | b7139483bb4735b7dfaf7e659ab33a16a90af1db |
Manually checked the links.
| [
"README.md"
] | |
juspay/hyperswitch | juspay__hyperswitch-5914 | Bug: [CYPRESS_FRAMEWORK] Run Cypress tests in parallel
**Description:**
Cypress tests are resource intensive and consume a lot of memory and power. But that should not stop us from running them in parallel even if they consume a lot of resources.
At present, Cypress tests here at Hyperswitch is run in sequential and consumes a lot of time given that each connector consumes at least 10+ mins and we've 10+ connector to run tests for.
With that said, the task is to parallelize the tests that are run and with that said, the consumption can be reduced drastically (1+ hour(s) to mere 15 mins).
> [!IMPORTANT]
> **Cypress cloud is a no go**
Below is the shell script that runs helps run the test in both sequential and parallel ways:
```sh
#!/bin/bash
CONNECTORS=("adyen" "bankofamerica" "bluesnap" "cybersource" "iatapay" "nmi" "paypal" "stripe" "trustpay")
# Function to run tests
run_tests() {
mkdir -p results
local pids=()
for connector in "${CONNECTORS[@]}"; do
if [[ $parallel == true ]]; then
CYPRESS_CONNECTOR="${connector}" npm run cypress:ci > results/${connector}.txt 2>&1 &
pids+=($!)
else
printf "\rRunning Cypress tests against the connector: ${connector}"
CYPRESS_CONNECTOR="${connector}" npm run cypress:ci > results/${connector}.txt 2>&1
local exit_code=$?
if [[ $exit_code -ne 0 && $exit_code -ge 128 ]]; then
exit 1
fi
sleep 3
fi
done
if [[ $parallel == true ]]; then
for pid in "${pids[@]}"; do
wait $pid
done
fi
}
# Check if running in parallel
if [[ "${1}" == "--parallel" ]]; then
printf "WARNING: Parallel tests are flaky and may not work as expected.\n"
eval run_tests true
else
eval run_tests false
fi
```
To execute the script:
```sh
# to run tests sequentially, which can take an hour+
sh run-cypress.sh
# to run tests in parallel, consumes around 15 - 20 mins, at the cost of resources
sh run-cypress.sh --parallel
```
**Getting started:**
Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress.
In short:
```sh
cd cypress-tests
npm ci
```
**Possible implementation:**
- Shell script above is attached for reference
- Make use of `gnu-parallel` to reduce the complexity of the script. The advantage here is that, it also make the script more future proof, manageable, easier to read and understand
- As a bonus, the same functionality can be implemented in JavaScript directly into Cypress via its configs is a plus
>[!WARNING]
> **Make sure that before this task is picked, the machine is capable enough to run at least 2 connector tests in parallel**. Running Cypress tests in parallel is too resource intensive!
> Please go through the Cypress [docs](https://docs.cypress.io/guides/getting-started/installing-cypress#CPU) to learn whether you're machine meets minimum requirements.
| diff --git a/scripts/execute_cypress.sh b/scripts/execute_cypress.sh
new file mode 100755
index 00000000000..1f1219ee717
--- /dev/null
+++ b/scripts/execute_cypress.sh
@@ -0,0 +1,188 @@
+#! /usr/bin/env bash
+
+set -euo pipefail
+
+# Initialize tmp_file globally
+tmp_file=""
+
+# Define arrays for services, etc.
+# Read service arrays from environment variables
+read -r -a payments <<< "${PAYMENTS_CONNECTORS[@]:-}"
+read -r -a payouts <<< "${PAYOUTS_CONNECTORS[@]:-}"
+read -r -a payment_method_list <<< "${PAYMENT_METHOD_LIST[@]:-}"
+read -r -a routing <<< "${ROUTING[@]:-}"
+
+# Define arrays
+connector_map=()
+failed_connectors=()
+
+# Define an associative array to map environment variables to service names
+declare -A services=(
+ ["PAYMENTS_CONNECTORS"]="payments"
+ ["PAYOUTS_CONNECTORS"]="payouts"
+ ["PAYMENT_METHOD_LIST"]="payment_method_list"
+ ["ROUTING"]="routing"
+)
+
+# Function to print messages in color
+function print_color() {
+ # Input params
+ local color="$1"
+ local message="$2"
+
+ # Define colors
+ local reset='\033[0m'
+ local red='\033[0;31m'
+ local green='\033[0;32m'
+ local yellow='\033[0;33m'
+
+ # Use indirect reference to get the color value
+ echo -e "${!color}${message}${reset}"
+}
+export -f print_color
+
+# Function to check if a command exists
+function command_exists() {
+ command -v "$1" > /dev/null 2>&1
+}
+
+# Function to read service arrays from environment variables
+function read_service_arrays() {
+ # Loop through the associative array and check if each service is exported
+ for var in "${!services[@]}"; do
+ if [[ -n "${!var+x}" ]]; then
+ connector_map+=("${services[$var]}")
+ else
+ print_color "yellow" "Environment variable ${var} is not set. Skipping..."
+ fi
+ done
+}
+
+# Function to execute Cypress tests
+function execute_test() {
+ if [[ $# -lt 3 ]]; then
+ print_color "red" "ERROR: Insufficient arguments provided to execute_test."
+ exit 1
+ fi
+
+ local connector="$1"
+ local service="$2"
+ local tmp_file="$3"
+
+ print_color "yellow" "Executing tests for ${service} with connector ${connector}..."
+
+ export REPORT_NAME="${service}_${connector}_report"
+
+ if ! CYPRESS_CONNECTOR="$connector" npm run "cypress:$service"; then
+ echo "${service}-${connector}" >> "${tmp_file}"
+ fi
+}
+export -f execute_test
+
+# Function to run tests
+function run_tests() {
+ local jobs="${1:-1}"
+ tmp_file=$(mktemp)
+
+ # Ensure temporary file is removed on script exit
+ trap 'cleanup' EXIT
+
+ for service in "${connector_map[@]}"; do
+ declare -n connectors="$service"
+
+ if [[ ${#connectors[@]} -eq 0 ]]; then
+ # Service-level test (e.g., payment-method-list or routing)
+ [[ $service == "payment_method_list" ]] && service="payment-method-list"
+
+ echo "Running ${service} tests without connectors..."
+ export REPORT_NAME="${service}_report"
+
+ if ! npm run "cypress:${service}"; then
+ echo "${service}" >> "${tmp_file}"
+ fi
+ else
+ # Connector-specific tests (e.g., payments or payouts)
+ print_color "yellow" "Running tests for service: '${service}' with connectors: [${connectors[*]}] in batches of ${jobs}..."
+
+ # Execute tests in parallel
+ printf '%s\n' "${connectors[@]}" | parallel --jobs "${jobs}" execute_test {} "${service}" "${tmp_file}"
+ fi
+ done
+
+ # Collect failed connectors
+ if [[ -s "${tmp_file}" ]]; then
+ failed_connectors=($(< "${tmp_file}"))
+ print_color "red" "One or more connectors failed to run:"
+ printf '%s\n' "${failed_connectors[@]}"
+ exit 1
+ else
+ print_color "green" "Cypress tests execution successful!"
+ fi
+}
+
+# Function to check and install dependencies
+function check_dependencies() {
+ # parallel and npm are mandatory dependencies. exit the script if not found.
+ local dependencies=("parallel" "npm")
+
+ for cmd in "${dependencies[@]}"; do
+ if ! command_exists "$cmd"; then
+ print_color "red" "ERROR: ${cmd^} is not installed!"
+ exit 1
+ else
+ print_color "green" "${cmd^} is installed already!"
+
+ if [[ ${cmd} == "npm" ]]; then
+ npm ci || {
+ print_color "red" "Command \`npm ci\` failed!"
+ exit 1
+ }
+ fi
+ fi
+ done
+}
+
+# Cleanup function to handle exit
+function cleanup() {
+ print_color "yellow" "Cleaning up..."
+ if [[ -d "cypress-tests" ]]; then
+ cd -
+ fi
+
+ if [[ -n "${tmp_file}" && -f "${tmp_file}" ]]; then
+ rm -f "${tmp_file}"
+ fi
+}
+
+# Main function
+function main() {
+ local command="${1:-}"
+ local jobs="${2:-5}"
+
+ # Ensure script runs from 'cypress-tests' directory
+ if [[ "$(basename "$PWD")" != "cypress-tests" ]]; then
+ print_color "yellow" "Changing directory to 'cypress-tests'..."
+ cd cypress-tests || {
+ print_color "red" "ERROR: Directory 'cypress-tests' not found!"
+ exit 1
+ }
+ fi
+
+ check_dependencies
+ read_service_arrays
+
+ case "$command" in
+ --parallel | -p)
+ print_color "yellow" "WARNING: Running Cypress tests in parallel is more resource-intensive!"
+ # At present, parallel execution is restricted to not run out of memory
+ # But can be scaled up by passing the value as an argument
+ run_tests "$jobs"
+ ;;
+ *)
+ run_tests 1
+ ;;
+ esac
+}
+
+# Execute the main function with passed arguments
+main "$@"
| 2024-10-04T09:33:14Z |
## Description
<!-- Describe your changes in detail -->
This PR makes it possible for us to run Cypress tests in parallel by leveraging `gnu-parallel`.
At present, we'll only be running against 5 connectors namely,
- payments: bluesnap, cybersource, stripe
- payouts: adyen and wise
w.r.t pml and other connectors, there are some failures within the tests that needs to be addressed.
>[!IMPORTANT]
> Cypress in parallel is resource heavy and running it in batch of 3+ will result in unintended consequences like abrupt failures due to resource limitation.
Running Cypress tests in parallel also puts up a challenge where when a specific test fails for 2 connectors at the same time, test against both the connectors stops abruptly. This is because of the file name conflict as we not have the privilege to change the names of the screenshots while capturing but only after the screenshot is captured.
To address this, the format of screenshot has been changed where screenshot directories are changed based on the connectors (just because we now have the privilege to change directories in real time).
Also, a similar issue with reports have also been addressed.
Documentation has been updated to address the usage of `scripts/execute_cypress.sh` script.
In short,
```sh
source .env
scripts/execute_cypress.sh --parallel <jobs_count>
```
>[!NOTE]
> make sure that service variables (PAYMENTS, PAYOUTS, PAYMENT_METHOD_LIST, ROUTING) is exported along with CYPRESS env variables in the `.env` file. Check README for more info.
> if `--parallel` is not passed, tests will run in sequential manner by setting jobs to `1`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
When Cypress tests are run in sequential, it takes about `1h10m+` to run against `10+` prod connectors. With `parallel`, we'll bring that down to nearly `15m`.
This should close https://github.com/juspay/hyperswitch/issues/5914
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested locally:
These are known failures.
<img width="576" alt="image" src="https://github.com/user-attachments/assets/12788d3f-f816-4395-9799-316546595823">
The ones that passed is `Stripe` and hence it is not in `failed_connector` list.
https://github.com/juspay/hyperswitch/actions/runs/11177572035/job/31077505520?pr=6225
https://github.com/juspay/hyperswitch/actions/runs/11384335020/job/31673789059 | d06d19fc96e1a74d20e2fe3613f86d541947e0ae |
Tested locally:
These are known failures.
<img width="576" alt="image" src="https://github.com/user-attachments/assets/12788d3f-f816-4395-9799-316546595823">
The ones that passed is `Stripe` and hence it is not in `failed_connector` list.
https://github.com/juspay/hyperswitch/actions/runs/11177572035/job/31077505520?pr=6225
https://github.com/juspay/hyperswitch/actions/runs/11384335020/job/31673789059
| [
"scripts/execute_cypress.sh"
] | |
juspay/hyperswitch | juspay__hyperswitch-6222 | Bug: bug(user_roles): Restrict updating user_roles to the same entity level
Currently update user role API allows updating a merchant level user role to profile level, which should not be possible.
This comes under upgrade/downgrade functionality, which is not available yet.
| diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index e10fa0eb81c..f2e9f758158 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -151,6 +151,14 @@ pub async fn update_user_role(
));
}
+ if role_info.get_entity_type() != role_to_be_updated.get_entity_type() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}",
+ role_to_be_updated.get_entity_type(),
+ role_info.get_entity_type(),
+ ));
+ }
+
if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Invalid operation, update requestor = {} cannot update target = {}",
@@ -216,6 +224,14 @@ pub async fn update_user_role(
));
}
+ if role_info.get_entity_type() != role_to_be_updated.get_entity_type() {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}",
+ role_to_be_updated.get_entity_type(),
+ role_info.get_entity_type(),
+ ));
+ }
+
if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Invalid operation, update requestor = {} cannot update target = {}",
| 2024-10-04T08:16:42Z |
## Description
<!-- Describe your changes in detail -->
- Currently update user role API allows updating a merchant level user role to profile level, which should not be possible.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6222.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```curl
curl --location 'http://localhost:8080/user/user/update_role' \
--header 'Authorization: JWT' \
--data-raw '{
"email": "merchant level user email",
"role_id": "profile_admin"
}'
```
This call should throw the following error.
```json
{
"error": {
"type": "invalid_request",
"message": "User Role Operation Not Supported",
"code": "UR_23"
}
}
``` | a3c2694943a985d27b5bc8b0371884d17a6ca34d |
```curl
curl --location 'http://localhost:8080/user/user/update_role' \
--header 'Authorization: JWT' \
--data-raw '{
"email": "merchant level user email",
"role_id": "profile_admin"
}'
```
This call should throw the following error.
```json
{
"error": {
"type": "invalid_request",
"message": "User Role Operation Not Supported",
"code": "UR_23"
}
}
```
| [
"crates/router/src/core/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6216 | Bug: [BUG] Docker Compose dev environment fails to setup hyperswitch-server
### Bug Description
`hyperswitch-hyperswitch-server-1` container stops abruptly without spinning up the server. Container can't find `protobuf-compiler` debian package and fails. Below are the logs of the container
```shell
➜ hyperswitch git:(main) docker logs hyperswitch-hyperswitch-server-1
Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package protobuf-compiler
```
Protobuf compiler mentioned here https://github.com/juspay/hyperswitch/blob/a3c2694943a985d27b5bc8b0371884d17a6ca34d/docker-compose-development.yml#L64
### Expected Behavior
`hyperswitch-hyperswitch-server-1` should run
### Actual Behavior
Container simply exits
```shell
➜ hyperswitch git:(main) docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3569baada69f rust:latest "apt-get install -y …" 3 minutes ago Exited (100) 3 minutes ago hyperswitch-hyperswitch-server-1
```
### Steps To Reproduce
1. Clone the repo on a new machine
2. Run `docker compose --file docker-compose-development.yml up -d`
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution: Debian 12
### 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/docker-compose-development.yml b/docker-compose-development.yml
index cf12982a9bd..3878f880b06 100644
--- a/docker-compose-development.yml
+++ b/docker-compose-development.yml
@@ -59,10 +59,12 @@ services:
### Application services
hyperswitch-server:
- image: rust:latest
- command: |
- apt-get install -y protobuf-compiler && \
- cargo run --bin router -- -f ./config/docker_compose.toml
+ build:
+ dockerfile_inline: |
+ FROM rust:latest
+ RUN apt-get update && \
+ apt-get install -y protobuf-compiler
+ command: cargo run --bin router -- -f ./config/docker_compose.toml
working_dir: /app
ports:
- "8080:8080"
| 2024-10-04T02:40:48Z |
## Description
<!-- Describe your changes in detail -->
Fixes: https://github.com/juspay/hyperswitch/issues/6216
Builds a docker image with protobuf for hyperswitch-server.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Refer here for the issue Fixes: https://github.com/juspay/hyperswitch/issues/6216
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
docker compose --file docker-compose-development.yml up -d | a3c2694943a985d27b5bc8b0371884d17a6ca34d |
docker compose --file docker-compose-development.yml up -d
| [
"docker-compose-development.yml"
] | |
juspay/hyperswitch | juspay__hyperswitch-6014 | Bug: [BUG] Add reference to Sepa Bank Transfer Next Customer Actions Responses
### Bug Description
Sepa bank transfer payment responses don't contain reference for the payment.
A reference is very important unique id for the payment reconciliation by the connectors. e.g. Stripe does create a payment reference but Hyperswitch does not pass it down as part of **next action** in the **create-payment** api call. Check below for the detailed request and response structures.
### Expected Behavior
The next action section of the response should display reference.
```
"next_action": {
"type": "display_bank_transfer_information",
"bank_transfer_steps_and_charges_details": {
"sepa_bank_instructions": {
"account_holder_name": "LOL GmbH",
"bic": "SOGEDEFFXXX",
"country": "DE",
"iban": "DEXXXXXXXXXXXXXXXX6",
"reference" : "HZDK38NZ88MC
},
"receiver": {
"amount_received": 0,
"amount_charged": null,
"amount_remaining": 60
}
}
}
```
### Actual Behavior
1. Add a stripe connector to process sepa bank transfer payments ( customers pay to IBAN asynchronously)
2. Create a payment
```
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: <apiKey>' \
--data-raw '{
"amount": 60,
"authentication_type": "no_three_ds",
"confirm": true,
"currency": "EUR",
"customer_id": "cus_2CMeBeWVAEo4CpobIIOW",
"payment_method": "bank_transfer",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_transfer": {
"sepa_bank_transfer" : {
"billing_details" : {
"email" : "gmail@rajanikanth.com",
"name" : "Rajanikanth"
},
"country" : "DE"
}
}
}
}'
```
The successful output :
```JSON
{
"payment_id": "pay_H38rD4DfWwKg6Omoi2j4",
"merchant_id": "merchant_1713521192",
"status": "requires_customer_action",
"amount": 60,
"net_amount": 60,
"amount_capturable": 60,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_H38rD4DfWwKg6Omoi2j4_secret_hrWAvfkxn8BxCA60muqK",
"created": "2024-04-22T13:40:07.848Z",
"currency": "EUR",
"customer_id": "cus_2CMeBeWVAEo4CpobIIOW",
"customer": {
"id": "cus_2CMeBeWVAEo4CpobIIOW",
"name": "R. Rajanikanth",
"email": "gmail@rajanikanth.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {},
"billing": null
},
"payment_token": "token_e6zWZTicyszgnSJOYfoD",
"shipping": null,
"billing": null,
"order_details": null,
"email": "gmail@rajanikanth.com",
"name": "R. Rajanikanth",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "display_bank_transfer_information",
"bank_transfer_steps_and_charges_details": {
"sepa_bank_instructions": {
"account_holder_name": "LOL GmbH",
"bic": "SOGEDEFFXXX",
"country": "DE",
"iban": "DE7XXXXXXXXX2713356"
},
"receiver": {
"amount_received": 0,
"amount_charged": null,
"amount_remaining": 60
}
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cus_2CMeBeWVAEo4CpobIIOW",
"created_at": 1713793207,
"expires": 1713796807,
"secret": "epk_af95122559b54d969745ec25d126fe76"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3P8N6KP6tL3tSvaR0C4oriJt",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3P8N6KP6tL3tSvaR0C4oriJt",
"payment_link": null,
"profile_id": "pro_47tvU9WWnp9JNx2Xm6TR",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_8CXOXTBeD2bS07s71M0R",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-04-22T13:55:07.848Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-04-22T13:40:08.953Z"
}
```
3. In above response, the reference in the next action is missing.
```
"next_action": {
"type": "display_bank_transfer_information",
"bank_transfer_steps_and_charges_details": {
"sepa_bank_instructions": {
"account_holder_name": "LOL GmbH",
"bic": "SOGEDEFFXXX",
"country": "DE",
"iban": "DEXXXXXXXXXXX32713356"
},
"receiver": {
"amount_received": 0,
"amount_charged": null,
"amount_remaining": 60
}
}
}
```
4. Although stripe creates a reference
```
Amount remaining : €0.60 EUR
BIC : SOGEDEFFXXX
IBAN : DE73977977789374832713356
Country: DE
Account holder name: LOL GmbH
Reference : HZDK38NZ88MC
```
5. `StripeBankTransferDetails` in the code has reference but it is not passed down as the api response.
### Steps To Reproduce
1. Add a stripe connector to process sepa bank transfer payments ( customers pay to IBAN asynchronously)
2. Create a bank transfer payment.
3. Observe the successful response.
### Context For The Bug
https://docs.stripe.com/api/payment_intents/object#payment_intent_object-next_action-display_bank_transfer_instructions-reference
### Environment
sandbox hyperswitch
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index fb679970f3d..c554245b936 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -18325,7 +18325,8 @@
"account_holder_name",
"bic",
"country",
- "iban"
+ "iban",
+ "reference"
],
"properties": {
"account_holder_name": {
@@ -18342,6 +18343,10 @@
"iban": {
"type": "string",
"example": "123456789"
+ },
+ "reference": {
+ "type": "string",
+ "example": "U2PVVSEV4V9Y"
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 23c3b219b65..cc6a9af5258 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3545,6 +3545,8 @@ pub struct SepaBankTransferInstructions {
pub country: String,
#[schema(value_type = String, example = "123456789")]
pub iban: Secret<String>,
+ #[schema(value_type = String, example = "U2PVVSEV4V9Y")]
+ pub reference: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 2129ad327c2..1a25075ce21 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2475,7 +2475,16 @@ pub fn get_connector_metadata(
let (sepa_bank_instructions, bacs_bank_instructions) =
bank_instructions.map_or((None, None), |financial_address| {
(
- financial_address.iban.to_owned(),
+ financial_address
+ .iban
+ .to_owned()
+ .map(|sepa_financial_details| SepaFinancialDetails {
+ account_holder_name: sepa_financial_details.account_holder_name,
+ bic: sepa_financial_details.bic,
+ country: sepa_financial_details.country,
+ iban: sepa_financial_details.iban,
+ reference: response.reference.to_owned(),
+ }),
financial_address.sort_code.to_owned(),
)
});
@@ -2880,6 +2889,7 @@ pub struct SepaFinancialDetails {
pub bic: Secret<String>,
pub country: Secret<String>,
pub iban: Secret<String>,
+ pub reference: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
| 2024-10-03T13:51:09Z |
## Description
<!-- Describe your changes in detail -->
'reference' added in sepa_bank_instructions, for Stripe Sepa Bank Transfer
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6014
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request
~~~
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: <apiKey>' \
--data-raw '{
"amount": 60,
"authentication_type": "no_three_ds",
"confirm": true,
"currency": "EUR",
"customer_id": "StripeCustomer",
"payment_method": "bank_transfer",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_transfer": {
"sepa_bank_transfer" : {
"billing_details" : {
"email" : "gmail@rajanikanth.com",
"name" : "Rajanikanth"
},
"country" : "DE"
}
}
}
}'
~~~
The successful output :
~~~
{
"payment_id": "pay_bLamnDrh3V3GefetEL3Tm",
"merchant_id": "merchant_1727948661",
"status": "requires_customer_action",
"amount": 60,
"net_amount": 60,
"amount_capturable": 60,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_bLamnDrh3V3cefctEL3Tm_secret_QsqbBrkZn2pI7cerfer",
"created": "2024-10-03T13:25:34.962Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {
"sepa": {}
},
"billing": null
},
"payment_token": "token_kwd45640isqRNJdwedwB",
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "display_bank_transfer_information",
"bank_transfer_steps_and_charges_details": {
"sepa_bank_instructions": {
"account_holder_name": "ABCD France",
"bic": "SOGEDEFFXXX",
"country": "DE",
"iban": "DE4039739XXXXXXXX89727",
"reference": "8NXKXQARUC9X"
},
"receiver": {
"amount_received": 0,
"amount_charged": null,
"amount_remaining": 60
}
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1727961934,
"expires": 1727965534,
"secret": "epk_f8ad2600b91b47bcaa762322eaa6f5f3"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou",
"payment_link": null,
"profile_id": "pro_TSOb6xQbAkCdcsTtYf6C",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_XjEZ8bwoCedxxxdE3u",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-03T13:40:34.962Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-03T13:25:36.680Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
~~~ | a3c2694943a985d27b5bc8b0371884d17a6ca34d |
Request
~~~
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: <apiKey>' \
--data-raw '{
"amount": 60,
"authentication_type": "no_three_ds",
"confirm": true,
"currency": "EUR",
"customer_id": "StripeCustomer",
"payment_method": "bank_transfer",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_transfer": {
"sepa_bank_transfer" : {
"billing_details" : {
"email" : "gmail@rajanikanth.com",
"name" : "Rajanikanth"
},
"country" : "DE"
}
}
}
}'
~~~
The successful output :
~~~
{
"payment_id": "pay_bLamnDrh3V3GefetEL3Tm",
"merchant_id": "merchant_1727948661",
"status": "requires_customer_action",
"amount": 60,
"net_amount": 60,
"amount_capturable": 60,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_bLamnDrh3V3cefctEL3Tm_secret_QsqbBrkZn2pI7cerfer",
"created": "2024-10-03T13:25:34.962Z",
"currency": "EUR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {
"sepa": {}
},
"billing": null
},
"payment_token": "token_kwd45640isqRNJdwedwB",
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "display_bank_transfer_information",
"bank_transfer_steps_and_charges_details": {
"sepa_bank_instructions": {
"account_holder_name": "ABCD France",
"bic": "SOGEDEFFXXX",
"country": "DE",
"iban": "DE4039739XXXXXXXX89727",
"reference": "8NXKXQARUC9X"
},
"receiver": {
"amount_received": 0,
"amount_charged": null,
"amount_remaining": 60
}
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1727961934,
"expires": 1727965534,
"secret": "epk_f8ad2600b91b47bcaa762322eaa6f5f3"
},
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou",
"payment_link": null,
"profile_id": "pro_TSOb6xQbAkCdcsTtYf6C",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_XjEZ8bwoCedxxxdE3u",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-03T13:40:34.962Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-03T13:25:36.680Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
~~~
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/payments.rs",
"crates/router/src/connector/stripe/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6213 | Bug: Payment method delete API for v2
| diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index af3c657c34a..445ad5ab800 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -14,6 +14,20 @@ use time::PrimitiveDateTime;
use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct VaultId(String);
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl VaultId {
+ pub fn get_string_repr(&self) -> &String {
+ &self.0
+ }
+
+ pub fn generate(id: String) -> Self {
+ Self(id)
+ }
+}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -67,7 +81,7 @@ pub struct PaymentMethod {
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: OptionalEncryptableValue,
- pub locker_id: Option<String>,
+ pub locker_id: Option<VaultId>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<pii::SecretSerdeValue>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
@@ -302,7 +316,7 @@ impl super::behaviour::Conversion for PaymentMethod {
payment_method_type: self.payment_method_type,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
- locker_id: self.locker_id,
+ locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
@@ -356,7 +370,7 @@ impl super::behaviour::Conversion for PaymentMethod {
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
- locker_id: item.locker_id,
+ locker_id: item.locker_id.map(VaultId::generate),
last_used_at: item.last_used_at,
connector_mandate_details: item.connector_mandate_details,
customer_acceptance: item.customer_acceptance,
@@ -415,7 +429,7 @@ impl super::behaviour::Conversion for PaymentMethod {
payment_method_type: self.payment_method_type,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
- locker_id: self.locker_id,
+ locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 1b93f05d823..721dd9de1c4 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -149,6 +149,26 @@ pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint";
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/vault/retrieve";
+/// Vault Delete request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_DELETE_REQUEST_URL: &str = "/vault/delete";
+
/// Vault Header content type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";
+
+/// Vault Add flow type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault";
+
+/// Vault Retrieve flow type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault";
+
+/// Vault Delete flow type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault";
+
+/// Vault Fingerprint fetch flow type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault";
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 8841ad7f383..9a093a065e4 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1124,7 +1124,7 @@ pub async fn create_payment_method_in_db(
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
- locker_id: Option<String>,
+ locker_id: Option<domain::VaultId>,
merchant_id: &id_type::MerchantId,
pm_metadata: Option<common_utils::pii::SecretSerdeValue>,
customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
@@ -1276,12 +1276,12 @@ pub async fn vault_payment_method(
pmd: &pm_types::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
- existing_vault_id: Option<String>,
+ existing_vault_id: Option<domain::VaultId>,
) -> RouterResult<pm_types::AddVaultResponse> {
let db = &*state.store;
- // get fingerprint_id from locker
- let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd)
+ // get fingerprint_id from vault
+ let fingerprint_id_from_vault = vault::get_fingerprint_id_from_vault(state, pmd)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get fingerprint_id from vault")?;
@@ -1292,7 +1292,7 @@ pub async fn vault_payment_method(
db.find_payment_method_by_fingerprint_id(
&(state.into()),
key_store,
- &fingerprint_id_from_locker,
+ &fingerprint_id_from_vault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -1305,13 +1305,13 @@ pub async fn vault_payment_method(
},
)?;
- let resp_from_locker =
- cards::vault_payment_method_in_locker(state, merchant_account, pmd, existing_vault_id)
+ let resp_from_vault =
+ vault::add_payment_method_to_vault(state, merchant_account, pmd, existing_vault_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to vault payment method in locker")?;
+ .attach_printable("Failed to add payment method in vault")?;
- Ok(resp_from_locker)
+ Ok(resp_from_vault)
}
#[cfg(all(
@@ -1339,10 +1339,12 @@ async fn get_pm_list_context(
storage::PaymentTokenData::permanent_card(
Some(pm.get_id().clone()),
pm.locker_id
- .clone()
+ .as_ref()
+ .map(|id| id.get_string_repr().clone())
.or(Some(pm.get_id().get_string_repr().to_owned())),
pm.locker_id
- .clone()
+ .as_ref()
+ .map(|id| id.get_string_repr().clone())
.unwrap_or(pm.get_id().get_string_repr().to_owned()),
),
),
@@ -1767,20 +1769,16 @@ pub async fn update_payment_method(
},
)?;
- let pmd: pm_types::PaymentMethodVaultingData = cards::retrieve_payment_method_from_vault(
- &state,
- &merchant_account,
- &payment_method.customer_id,
- &payment_method,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to retrieve payment method from vault")?
- .data
- .expose()
- .parse_struct("PaymentMethodCreateData")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to parse PaymentMethodCreateData")?;
+ let pmd: pm_types::PaymentMethodVaultingData =
+ vault::retrieve_payment_method_from_vault(&state, &merchant_account, &payment_method)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve payment method from vault")?
+ .data
+ .expose()
+ .parse_struct("PaymentMethodVaultingData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse PaymentMethodVaultingData")?;
let vault_request_data =
pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, req.payment_method_data);
@@ -1825,6 +1823,76 @@ pub async fn update_payment_method(
Ok(services::ApplicationResponse::Json(response))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn delete_payment_method(
+ state: SessionState,
+ pm_id: api::PaymentMethodId,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+) -> RouterResponse<api::PaymentMethodDeleteResponse> {
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = db
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let vault_id = payment_method
+ .locker_id
+ .clone()
+ .get_required_value("locker_id")
+ .attach_printable("Missing locker_id in PaymentMethod")?;
+
+ let _customer = db
+ .find_customer_by_global_id(
+ key_manager_state,
+ payment_method.customer_id.get_string_repr(),
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Customer not found for the payment method")?;
+
+ // Soft delete
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+ db.update_payment_method(
+ &((&state).into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ vault::delete_payment_method_data_from_vault(&state, &merchant_account, vault_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to delete payment method from vault")?;
+
+ let response = api::PaymentMethodDeleteResponse {
+ payment_method_id: pm_id.get_string_repr().to_string(),
+ };
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl pm_types::SavedPMLPaymentsInfo {
pub async fn form_payments_info(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 3c09db61a39..5f931205931 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -221,37 +221,6 @@ pub async fn create_payment_method(
Ok(response)
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-async fn create_vault_request<R: pm_types::VaultingInterface>(
- jwekey: &settings::Jwekey,
- locker: &settings::Locker,
- payload: Vec<u8>,
-) -> errors::CustomResult<Request, errors::VaultError> {
- let private_key = jwekey.vault_private_key.peek().as_bytes();
-
- let jws = services::encryption::jws_sign_payload(
- &payload,
- &locker.locker_signing_key_id,
- private_key,
- )
- .await
- .change_context(errors::VaultError::RequestEncryptionFailed)?;
-
- let jwe_payload = payment_methods::create_jwe_body_for_vault(jwekey, &jws).await?;
-
- let mut url = locker.host.to_owned();
- url.push_str(R::get_vaulting_request_url());
- let mut request = Request::new(services::Method::Post, &url);
- request.add_header(
- headers::CONTENT_TYPE,
- router_consts::VAULT_HEADER_CONTENT_TYPE.into(),
- );
- request.set_body(common_utils::request::RequestContent::Json(Box::new(
- jwe_payload,
- )));
- Ok(request)
-}
-
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -1411,107 +1380,6 @@ pub async fn add_payment_method(
Ok(services::ApplicationResponse::Json(resp))
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn get_fingerprint_id_from_locker<
- D: pm_types::VaultingDataInterface + serde::Serialize,
->(
- state: &routes::SessionState,
- data: &D,
-) -> errors::CustomResult<String, errors::VaultError> {
- let key = data.get_vaulting_data_key();
- let data = serde_json::to_value(data)
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode Vaulting data to value")?
- .to_string();
-
- let payload = pm_types::VaultFingerprintRequest { key, data }
- .encode_to_vec()
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode VaultFingerprintRequest")?;
-
- let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Failed to get response from locker")?;
-
- let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
- .parse_struct("VaultFingerprintResp")
- .change_context(errors::VaultError::ResponseDeserializationFailed)
- .attach_printable("Failed to parse data into VaultFingerprintResp")?;
-
- Ok(fingerprint_resp.fingerprint_id)
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn vault_payment_method_in_locker(
- state: &routes::SessionState,
- merchant_account: &domain::MerchantAccount,
- pmd: &pm_types::PaymentMethodVaultingData,
- existing_vault_id: Option<String>,
-) -> errors::CustomResult<pm_types::AddVaultResponse, errors::VaultError> {
- let payload = pm_types::AddVaultRequest {
- entity_id: merchant_account.get_id().to_owned(),
- vault_id: pm_types::VaultId::generate(
- existing_vault_id.unwrap_or(uuid::Uuid::now_v7().to_string()),
- ),
- data: pmd,
- ttl: state.conf.locker.ttl_for_storage_in_secs,
- }
- .encode_to_vec()
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode AddVaultRequest")?;
-
- let resp = call_to_vault::<pm_types::AddVault>(state, payload)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Failed to get response from locker")?;
-
- let stored_pm_resp: pm_types::AddVaultResponse = resp
- .parse_struct("AddVaultResponse")
- .change_context(errors::VaultError::ResponseDeserializationFailed)
- .attach_printable("Failed to parse data into AddVaultResponse")?;
-
- Ok(stored_pm_resp)
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn retrieve_payment_method_from_vault(
- state: &routes::SessionState,
- merchant_account: &domain::MerchantAccount,
- customer_id: &id_type::CustomerId,
- pm: &domain::PaymentMethod,
-) -> errors::CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
- let payload = pm_types::VaultRetrieveRequest {
- entity_id: merchant_account.get_id().to_owned(),
- vault_id: pm_types::VaultId::generate(
- pm.locker_id
- .clone()
- .ok_or(errors::VaultError::MissingRequiredField {
- field_name: "locker_id",
- })
- .attach_printable("Missing locker_id for VaultRetrieveRequest")?,
- ),
- }
- .encode_to_vec()
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode VaultRetrieveRequest")?;
-
- let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Failed to get response from locker")?;
-
- let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
- .parse_struct("VaultRetrieveResponse")
- .change_context(errors::VaultError::ResponseDeserializationFailed)
- .attach_printable("Failed to parse data into VaultRetrieveResponse")?;
-
- Ok(stored_pm_resp)
-}
-
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -2266,37 +2134,6 @@ pub async fn add_card_to_hs_locker(
Ok(stored_card)
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn call_to_vault<V: pm_types::VaultingInterface>(
- state: &routes::SessionState,
- payload: Vec<u8>,
-) -> errors::CustomResult<String, errors::VaultError> {
- let locker = &state.conf.locker;
- let jwekey = state.conf.jwekey.get_inner();
-
- let request = create_vault_request::<V>(jwekey, locker, payload).await?;
- let response = services::call_connector_api(state, request, "vault_in_locker")
- .await
- .change_context(errors::VaultError::VaultAPIError);
-
- let jwe_body: services::JweBody = response
- .get_response_inner("JweBody")
- .change_context(errors::VaultError::ResponseDeserializationFailed)
- .attach_printable("Failed to get JweBody from vault response")?;
-
- let decrypted_payload = payment_methods::get_decrypted_vault_response_payload(
- jwekey,
- jwe_body,
- locker.decryption_scheme.clone(),
- )
- .await
- .change_context(errors::VaultError::ResponseDecryptionFailed)
- .attach_printable("Error getting decrypted vault response payload")?;
-
- Ok(decrypted_payload)
-}
-
#[instrument(skip_all)]
pub async fn call_locker_api<T>(
state: &routes::SessionState,
@@ -5401,21 +5238,6 @@ pub async fn retrieve_payment_method(
))
}
-#[cfg(all(
- any(feature = "v2", feature = "v1"),
- not(feature = "payment_methods_v2")
-))]
-#[instrument(skip_all)]
-#[cfg(all(feature = "v2", feature = "customer_v2"))]
-pub async fn delete_payment_method(
- _state: routes::SessionState,
- _merchant_account: domain::MerchantAccount,
- _pm_id: api::PaymentMethodId,
- _key_store: domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
- todo!()
-}
-
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[instrument(skip_all)]
pub async fn delete_payment_method(
@@ -5518,17 +5340,6 @@ pub async fn delete_payment_method(
))
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn delete_payment_method(
- _state: routes::SessionState,
- _merchant_account: domain::MerchantAccount,
- _pm_id: api::PaymentMethodId,
- _key_store: domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
- todo!()
-}
-
pub async fn create_encrypted_data<T>(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 75278010ceb..7a24f2a30a2 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1,4 +1,6 @@
use common_enums::PaymentMethodType;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::request;
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
ext_traits::{BytesExt, Encode},
@@ -23,6 +25,11 @@ use crate::{
},
utils::StringExt,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ core::payment_methods::transformers as pm_transforms, headers, services, settings,
+ types::payment_methods as pm_types, utils::ConnectorResponseExt,
+};
const VAULT_SERVICE_NAME: &str = "CARD";
pub struct SupplementaryVaultData {
@@ -1172,6 +1179,191 @@ pub async fn delete_tokenized_data(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn create_vault_request<R: pm_types::VaultingInterface>(
+ jwekey: &settings::Jwekey,
+ locker: &settings::Locker,
+ payload: Vec<u8>,
+) -> CustomResult<request::Request, errors::VaultError> {
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
+
+ let jws = services::encryption::jws_sign_payload(
+ &payload,
+ &locker.locker_signing_key_id,
+ private_key,
+ )
+ .await
+ .change_context(errors::VaultError::RequestEncryptionFailed)?;
+
+ let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?;
+
+ let mut url = locker.host.to_owned();
+ url.push_str(R::get_vaulting_request_url());
+ let mut request = request::Request::new(services::Method::Post, &url);
+ request.add_header(
+ headers::CONTENT_TYPE,
+ consts::VAULT_HEADER_CONTENT_TYPE.into(),
+ );
+ request.set_body(request::RequestContent::Json(Box::new(jwe_payload)));
+ Ok(request)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn call_to_vault<V: pm_types::VaultingInterface>(
+ state: &routes::SessionState,
+ payload: Vec<u8>,
+) -> CustomResult<String, errors::VaultError> {
+ let locker = &state.conf.locker;
+ let jwekey = state.conf.jwekey.get_inner();
+
+ let request = create_vault_request::<V>(jwekey, locker, payload).await?;
+ let response = services::call_connector_api(state, request, V::get_vaulting_flow_name())
+ .await
+ .change_context(errors::VaultError::VaultAPIError);
+
+ let jwe_body: services::JweBody = response
+ .get_response_inner("JweBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to get JweBody from vault response")?;
+
+ let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload(
+ jwekey,
+ jwe_body,
+ locker.decryption_scheme.clone(),
+ )
+ .await
+ .change_context(errors::VaultError::ResponseDecryptionFailed)
+ .attach_printable("Error getting decrypted vault response payload")?;
+
+ Ok(decrypted_payload)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn get_fingerprint_id_from_vault<
+ D: pm_types::VaultingDataInterface + serde::Serialize,
+>(
+ state: &routes::SessionState,
+ data: &D,
+) -> CustomResult<String, errors::VaultError> {
+ let key = data.get_vaulting_data_key();
+ let data = serde_json::to_string(data)
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode Vaulting data to string")?;
+
+ let payload = pm_types::VaultFingerprintRequest { key, data }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultFingerprintRequest")?;
+
+ let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
+ .parse_struct("VaultFingerprintResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultFingerprintResponse")?;
+
+ Ok(fingerprint_resp.fingerprint_id)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn add_payment_method_to_vault(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ pmd: &pm_types::PaymentMethodVaultingData,
+ existing_vault_id: Option<domain::VaultId>,
+) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> {
+ let payload = pm_types::AddVaultRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id: existing_vault_id
+ .unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())),
+ data: pmd,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode AddVaultRequest")?;
+
+ let resp = call_to_vault::<pm_types::AddVault>(state, payload)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let stored_pm_resp: pm_types::AddVaultResponse = resp
+ .parse_struct("AddVaultResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into AddVaultResponse")?;
+
+ Ok(stored_pm_resp)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method_from_vault(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ pm: &domain::PaymentMethod,
+) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
+ let payload = pm_types::VaultRetrieveRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id: pm
+ .locker_id
+ .clone()
+ .ok_or(errors::VaultError::MissingRequiredField {
+ field_name: "locker_id",
+ })
+ .attach_printable("Missing locker_id for VaultRetrieveRequest")?,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultRetrieveRequest")?;
+
+ let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
+ .parse_struct("VaultRetrieveResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultRetrieveResponse")?;
+
+ Ok(stored_pm_resp)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn delete_payment_method_data_from_vault(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ vault_id: domain::VaultId,
+) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> {
+ let payload = pm_types::VaultDeleteRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id,
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultDeleteRequest")?;
+
+ let resp = call_to_vault::<pm_types::VaultDelete>(state, payload)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")?;
+
+ let stored_pm_resp: pm_types::VaultDeleteResponse = resp
+ .parse_struct("VaultDeleteResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultDeleteResponse")?;
+
+ Ok(stored_pm_resp)
+}
+
// ********************************************** PROCESS TRACKER **********************************************
pub async fn add_delete_tokenized_data_task(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 54e4471b057..c267b113fcd 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1091,7 +1091,8 @@ impl PaymentMethods {
web::resource("/{id}/update_saved_payment_method")
.route(web::patch().to(payment_method_update_api)),
)
- .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api)));
+ .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api)))
+ .service(web::resource("/{id}").route(web::delete().to(payment_method_delete_api)));
route
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 3e3aada154f..77c072448a2 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -14,8 +14,9 @@ use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use crate::core::payment_methods::{
- create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm,
- payment_method_intent_create, retrieve_payment_method, update_payment_method,
+ create_payment_method, delete_payment_method, list_customer_payment_method_util,
+ payment_method_intent_confirm, payment_method_intent_create, retrieve_payment_method,
+ update_payment_method,
};
use crate::{
core::{
@@ -239,6 +240,33 @@ pub async fn payment_method_retrieve_api(
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
+pub async fn payment_method_delete_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsDelete;
+ let payload = web::Json(PaymentMethodId {
+ payment_method_id: path.into_inner(),
+ })
+ .into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, pm, _| {
+ delete_payment_method(state, pm, auth.key_store, auth.merchant_account)
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
@@ -796,6 +824,10 @@ pub async fn payment_method_update_api(
.await
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))]
pub async fn payment_method_delete_api(
state: web::Data<AppState>,
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
index a1c0f8156fa..29290f0b7fc 100644
--- a/crates/router/src/types/payment_methods.rs
+++ b/crates/router/src/types/payment_methods.rs
@@ -10,32 +10,17 @@ use crate::{
};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
pub trait VaultingInterface {
fn get_vaulting_request_url() -> &'static str;
+
+ fn get_vaulting_flow_name() -> &'static str;
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
pub trait VaultingDataInterface {
fn get_vaulting_data_key(&self) -> String;
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct VaultId(String);
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-impl VaultId {
- pub fn get_string_repr(&self) -> &String {
- &self.0
- }
-
- pub fn generate(id: String) -> Self {
- Self(id)
- }
-}
-
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequest {
@@ -53,7 +38,7 @@ pub struct VaultFingerprintResponse {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultRequest<D> {
pub entity_id: common_utils::id_type::MerchantId,
- pub vault_id: VaultId,
+ pub vault_id: domain::VaultId,
pub data: D,
pub ttl: i64,
}
@@ -62,7 +47,7 @@ pub struct AddVaultRequest<D> {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultResponse {
pub entity_id: common_utils::id_type::MerchantId,
- pub vault_id: VaultId,
+ pub vault_id: domain::VaultId,
pub fingerprint_id: Option<String>,
}
@@ -79,27 +64,51 @@ pub struct GetVaultFingerprint;
pub struct VaultRetrieve;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultDelete;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl VaultingInterface for AddVault {
fn get_vaulting_request_url() -> &'static str {
consts::ADD_VAULT_REQUEST_URL
}
+
+ fn get_vaulting_flow_name() -> &'static str {
+ consts::VAULT_ADD_FLOW_TYPE
+ }
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
impl VaultingInterface for GetVaultFingerprint {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_FINGERPRINT_REQUEST_URL
}
+
+ fn get_vaulting_flow_name() -> &'static str {
+ consts::VAULT_GET_FINGERPRINT_FLOW_TYPE
+ }
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
impl VaultingInterface for VaultRetrieve {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_RETRIEVE_REQUEST_URL
}
+
+ fn get_vaulting_flow_name() -> &'static str {
+ consts::VAULT_RETRIEVE_FLOW_TYPE
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl VaultingInterface for VaultDelete {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::VAULT_DELETE_REQUEST_URL
+ }
+
+ fn get_vaulting_flow_name() -> &'static str {
+ consts::VAULT_DELETE_FLOW_TYPE
+ }
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
@@ -109,7 +118,6 @@ pub enum PaymentMethodVaultingData {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[async_trait::async_trait]
impl VaultingDataInterface for PaymentMethodVaultingData {
fn get_vaulting_data_key(&self) -> String {
match &self {
@@ -141,7 +149,7 @@ pub struct SavedPMLPaymentsInfo {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveRequest {
pub entity_id: common_utils::id_type::MerchantId,
- pub vault_id: VaultId,
+ pub vault_id: domain::VaultId,
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
@@ -149,3 +157,17 @@ pub struct VaultRetrieveRequest {
pub struct VaultRetrieveResponse {
pub data: Secret<String>,
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultDeleteRequest {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: domain::VaultId,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultDeleteResponse {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: domain::VaultId,
+}
| 2024-10-03T11:11:50Z |
## Description
<!-- Describe your changes in detail -->
- Payment method delete API for v2
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cannot be tested as vault dev is incomplete. | edd099886da9c46800a646fe809796a08eb78c99 |
Cannot be tested as vault dev is incomplete.
| [
"crates/hyperswitch_domain_models/src/payment_methods.rs",
"crates/router/src/consts.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payment_methods/vault.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/paymen... | |
juspay/hyperswitch | juspay__hyperswitch-6205 | Bug: [FIX] batch encrypt decrypt for mca fetch/insert/update
This adds batch encryption/decryption support for fetch/insert/update of the Merchant Connector Account. | diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index a281c553a13..66b98389818 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -4,14 +4,15 @@ use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii, type_name,
- types::keymanager::{Identifier, KeyManagerState},
+ types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
+use rustc_hash::FxHashMap;
use super::behaviour;
-use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation};
+use crate::type_encryption::{crypto_operation, CryptoOperation};
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
@@ -175,21 +176,33 @@ impl behaviour::Conversion for MerchantConnectorAccount {
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
+ let decrypted_data = crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca {
+ connector_account_details: other.connector_account_details,
+ additional_merchant_data: other.additional_merchant_data,
+ connector_wallets_details: other.connector_wallets_details,
+ })),
+ identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting connector account details".to_string(),
+ })?;
+
+ let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context(
+ ValidationError::InvalidValue {
+ message: "Failed while decrypting connector account details".to_string(),
+ },
+ )?;
+
Ok(Self {
merchant_id: other.merchant_id,
connector_name: other.connector_name,
- connector_account_details: crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::Decrypt(other.connector_account_details),
- identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting connector account details".to_string(),
- })?,
+ connector_account_details: decrypted_data.connector_account_details,
test_mode: other.test_mode,
disabled: other.disabled,
merchant_connector_id: other.merchant_connector_id,
@@ -213,41 +226,8 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
- connector_wallets_details: other
- .connector_wallets_details
- .async_lift(|inner| async {
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::DecryptOptional(inner),
- identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- })
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting connector wallets details".to_string(),
- })?,
- additional_merchant_data: if let Some(data) = other.additional_merchant_data {
- Some(
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::Decrypt(data),
- identifier,
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting additional_merchant_data".to_string(),
- })?,
- )
- } else {
- None
- },
+ connector_wallets_details: decrypted_data.connector_wallets_details,
+ additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
})
}
@@ -324,22 +304,35 @@ impl behaviour::Conversion for MerchantConnectorAccount {
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
+
+ let decrypted_data = crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca {
+ connector_account_details: other.connector_account_details,
+ additional_merchant_data: other.additional_merchant_data,
+ connector_wallets_details: other.connector_wallets_details,
+ })),
+ identifier.clone(),
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting connector account details".to_string(),
+ })?;
+
+ let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context(
+ ValidationError::InvalidValue {
+ message: "Failed while decrypting connector account details".to_string(),
+ },
+ )?;
+
Ok(Self {
id: other.id,
merchant_id: other.merchant_id,
connector_name: other.connector_name,
- connector_account_details: crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::Decrypt(other.connector_account_details),
- identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting connector account details".to_string(),
- })?,
+ connector_account_details: decrypted_data.connector_account_details,
disabled: other.disabled,
payment_methods_enabled: other.payment_methods_enabled,
connector_type: other.connector_type,
@@ -354,41 +347,8 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
- connector_wallets_details: other
- .connector_wallets_details
- .async_lift(|inner| async {
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::DecryptOptional(inner),
- identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- })
- .await
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting connector wallets details".to_string(),
- })?,
- additional_merchant_data: if let Some(data) = other.additional_merchant_data {
- Some(
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::Decrypt(data),
- identifier,
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(ValidationError::InvalidValue {
- message: "Failed while decrypting additional_merchant_data".to_string(),
- })?,
- )
- } else {
- None
- },
+ connector_wallets_details: decrypted_data.connector_wallets_details,
+ additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
})
}
@@ -542,3 +502,121 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
}
}
}
+
+pub struct McaFromRequestfromUpdate {
+ pub connector_account_details: Option<pii::SecretSerdeValue>,
+ pub connector_wallets_details: Option<pii::SecretSerdeValue>,
+ pub additional_merchant_data: Option<pii::SecretSerdeValue>,
+}
+pub struct McaFromRequest {
+ pub connector_account_details: pii::SecretSerdeValue,
+ pub connector_wallets_details: Option<pii::SecretSerdeValue>,
+ pub additional_merchant_data: Option<pii::SecretSerdeValue>,
+}
+
+pub struct DecryptedMca {
+ pub connector_account_details: Encryptable<pii::SecretSerdeValue>,
+ pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+}
+
+pub struct EncryptedMca {
+ pub connector_account_details: Encryption,
+ pub connector_wallets_details: Option<Encryption>,
+ pub additional_merchant_data: Option<Encryption>,
+}
+
+pub struct DecryptedUpdateMca {
+ pub connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+}
+
+impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Encryption> for EncryptedMca {
+ fn from_encryptable(
+ mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>,
+ ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> {
+ Ok(DecryptedMca {
+ connector_account_details: hashmap.remove("connector_account_details").ok_or(
+ error_stack::report!(common_utils::errors::ParsingError::EncodeError(
+ "Unable to convert from HashMap to DecryptedMca",
+ )),
+ )?,
+ connector_wallets_details: hashmap.remove("connector_wallets_details"),
+ additional_merchant_data: hashmap.remove("additional_merchant_data"),
+ })
+ }
+
+ fn to_encryptable(self) -> FxHashMap<String, Encryption> {
+ let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default());
+
+ map.insert(
+ "connector_account_details".to_string(),
+ self.connector_account_details,
+ );
+ self.connector_wallets_details
+ .map(|s| map.insert("connector_wallets_details".to_string(), s));
+ self.additional_merchant_data
+ .map(|s| map.insert("additional_merchant_data".to_string(), s));
+ map
+ }
+}
+
+impl ToEncryptable<DecryptedUpdateMca, Secret<serde_json::Value>, Secret<serde_json::Value>>
+ for McaFromRequestfromUpdate
+{
+ fn from_encryptable(
+ mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>,
+ ) -> CustomResult<DecryptedUpdateMca, common_utils::errors::ParsingError> {
+ Ok(DecryptedUpdateMca {
+ connector_account_details: hashmap.remove("connector_account_details"),
+ connector_wallets_details: hashmap.remove("connector_wallets_details"),
+ additional_merchant_data: hashmap.remove("additional_merchant_data"),
+ })
+ }
+
+ fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> {
+ let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default());
+
+ self.connector_account_details
+ .map(|cad| map.insert("connector_account_details".to_string(), cad));
+
+ self.connector_wallets_details
+ .map(|s| map.insert("connector_wallets_details".to_string(), s));
+ self.additional_merchant_data
+ .map(|s| map.insert("additional_merchant_data".to_string(), s));
+ map
+ }
+}
+
+impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Secret<serde_json::Value>>
+ for McaFromRequest
+{
+ fn from_encryptable(
+ mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>,
+ ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> {
+ Ok(DecryptedMca {
+ connector_account_details: hashmap.remove("connector_account_details").ok_or(
+ error_stack::report!(common_utils::errors::ParsingError::EncodeError(
+ "Unable to convert from HashMap to DecryptedMca",
+ )),
+ )?,
+ connector_wallets_details: hashmap.remove("connector_wallets_details"),
+ additional_merchant_data: hashmap.remove("additional_merchant_data"),
+ })
+ }
+
+ fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> {
+ let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default());
+
+ map.insert(
+ "connector_account_details".to_string(),
+ self.connector_account_details,
+ );
+ self.connector_wallets_details
+ .map(|s| map.insert("connector_wallets_details".to_string(), s));
+ self.additional_merchant_data
+ .map(|s| map.insert("additional_merchant_data".to_string(), s));
+ map
+ }
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index b988578d35e..fed284955b3 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -8,12 +8,15 @@ use common_utils::{
date_time,
ext_traits::{AsyncExt, Encode, OptionExt, ValueExt},
id_type, pii, type_name,
- types::keymanager::{self as km_types, KeyManagerState},
+ types::keymanager::{self as km_types, KeyManagerState, ToEncryptable},
};
use diesel_models::configs;
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))]
use diesel_models::organization::OrganizationBridge;
use error_stack::{report, FutureExt, ResultExt};
+use hyperswitch_domain_models::merchant_connector_account::{
+ McaFromRequest, McaFromRequestfromUpdate,
+};
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types};
use regex::Regex;
@@ -2089,25 +2092,37 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
+ let encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable(
+ McaFromRequestfromUpdate {
+ connector_account_details: self.connector_account_details,
+ connector_wallets_details:
+ helpers::get_connector_wallets_details_with_apple_pay_certificates(
+ &self.metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
+ additional_merchant_data: merchant_recipient_data.map(Secret::new),
+ },
+ )),
+ km_types::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details".to_string())?;
+
+ let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details")?;
+
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_label: self.connector_label.clone(),
- connector_account_details: self
- .connector_account_details
- .async_lift(|inner| async {
- domain_types::crypto_operation(
- key_manager_state,
- type_name!(storage::MerchantConnectorAccount),
- domain_types::CryptoOperation::EncryptOptional(inner),
- km_types::Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- })
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while encrypting data")?,
+ connector_account_details: encrypted_data.connector_account_details,
disabled,
payment_methods_enabled,
metadata: self.metadata,
@@ -2123,31 +2138,8 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config,
status: Some(connector_status),
- additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(
- domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
- km_types::Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt additional_merchant_data")?,
- )
- } else {
- None
- },
- connector_wallets_details:
- helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(
- state,
- &key_store,
- &metadata,
- &self.connector_wallets_details,
- )
- .await?,
+ additional_merchant_data: encrypted_data.additional_merchant_data,
+ connector_wallets_details: encrypted_data.connector_wallets_details,
})
}
}
@@ -2267,27 +2259,39 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
+ let encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable(
+ McaFromRequestfromUpdate {
+ connector_account_details: self.connector_account_details,
+ connector_wallets_details:
+ helpers::get_connector_wallets_details_with_apple_pay_certificates(
+ &self.metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
+ additional_merchant_data: merchant_recipient_data.map(Secret::new),
+ },
+ )),
+ km_types::Identifier::Merchant(key_store.merchant_id.clone()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details".to_string())?;
+
+ let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details")?;
+
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_name: None,
merchant_connector_id: None,
connector_label: self.connector_label.clone(),
- connector_account_details: self
- .connector_account_details
- .async_lift(|inner| async {
- domain_types::crypto_operation(
- key_manager_state,
- type_name!(storage::MerchantConnectorAccount),
- domain_types::CryptoOperation::EncryptOptional(inner),
- km_types::Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- })
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while encrypting data")?,
+ connector_account_details: encrypted_data.connector_account_details,
test_mode: self.test_mode,
disabled,
payment_methods_enabled,
@@ -2304,31 +2308,8 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config,
status: Some(connector_status),
- additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(
- domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
- km_types::Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt additional_merchant_data")?,
- )
- } else {
- None
- },
- connector_wallets_details:
- helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(
- state,
- &key_store,
- &metadata,
- &self.connector_wallets_details,
- )
- .await?,
+ additional_merchant_data: encrypted_data.additional_merchant_data,
+ connector_wallets_details: encrypted_data.connector_wallets_details,
})
}
}
@@ -2417,25 +2398,43 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
+
+ let encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable(
+ McaFromRequest {
+ connector_account_details: self.connector_account_details.ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "connector_account_details",
+ },
+ )?,
+ connector_wallets_details:
+ helpers::get_connector_wallets_details_with_apple_pay_certificates(
+ &self.metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
+ additional_merchant_data: merchant_recipient_data.map(Secret::new),
+ },
+ )),
+ identifier.clone(),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details".to_string())?;
+
+ let encrypted_data = McaFromRequest::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details")?;
+
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
- connector_account_details: domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or(
- errors::ApiErrorResponse::MissingRequiredField {
- field_name: "connector_account_details",
- },
- )?),
- identifier.clone(),
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt connector account details")?,
+ connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
@@ -2459,22 +2458,8 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
- connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?,
- additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
- km_types::Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt additional_merchant_data")?)
- } else {
- None
- },
+ connector_wallets_details: encrypted_data.connector_wallets_details,
+ additional_merchant_data: encrypted_data.additional_merchant_data,
version: hyperswitch_domain_models::consts::API_VERSION,
})
}
@@ -2582,26 +2567,44 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
+
+ let encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(domain::MerchantConnectorAccount),
+ domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable(
+ McaFromRequest {
+ connector_account_details: self.connector_account_details.ok_or(
+ errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "connector_account_details",
+ },
+ )?,
+ connector_wallets_details:
+ helpers::get_connector_wallets_details_with_apple_pay_certificates(
+ &self.metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
+ additional_merchant_data: merchant_recipient_data.map(Secret::new),
+ },
+ )),
+ identifier.clone(),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details".to_string())?;
+
+ let encrypted_data = McaFromRequest::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while decrypting connector account details")?;
+
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(),
- connector_account_details: domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or(
- errors::ApiErrorResponse::MissingRequiredField {
- field_name: "connector_account_details",
- },
- )?),
- identifier.clone(),
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt connector account details")?,
+ connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
@@ -2624,26 +2627,12 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
- connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?,
+ connector_wallets_details: encrypted_data.connector_wallets_details,
test_mode: self.test_mode,
business_country: self.business_country,
business_label: self.business_label.clone(),
business_sub_label: self.business_sub_label.clone(),
- additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
- Some(domain_types::crypto_operation(
- key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- domain_types::CryptoOperation::Encrypt(Secret::new(mcd)),
- identifier,
- key_store.key.peek(),
- )
- .await
- .and_then(|val| val.try_into_operation())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt additional_merchant_data")?)
- } else {
- None
- },
+ additional_merchant_data: encrypted_data.additional_merchant_data,
version: hyperswitch_domain_models::consts::API_VERSION,
})
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 3782026835b..f0b1e9ca86e 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -76,10 +76,7 @@ use crate::{
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
- domain::{
- self,
- types::{self, AsyncLift},
- },
+ domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
@@ -4534,12 +4531,10 @@ pub fn is_apple_pay_simplified_flow(
// As part of migration fallback this function checks apple pay details are present in connector_wallets_details
// If yes, it will encrypt connector_wallets_details and store it in the database.
// If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it.
-pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates(
- state: &SessionState,
- key_store: &domain::MerchantKeyStore,
+pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
-) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> {
+) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
let connector_wallet_details_with_apple_pay_metadata_optional =
get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
.await?;
@@ -4553,25 +4548,7 @@ pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates
.transpose()?
.map(masking::Secret::new);
- let key_manager_state: KeyManagerState = state.into();
- let encrypted_connector_wallets_details = connector_wallets_details
- .clone()
- .async_lift(|wallets_details| async {
- types::crypto_operation(
- &key_manager_state,
- type_name!(domain::MerchantConnectorAccount),
- types::CryptoOperation::EncryptOptional(wallets_details),
- Identifier::Merchant(key_store.merchant_id.clone()),
- key_store.key.get_inner().peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- })
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while encrypting connector wallets details")?;
-
- Ok(encrypted_connector_wallets_details)
+ Ok(connector_wallets_details)
}
async fn get_apple_pay_metadata_if_needed(
| 2024-10-03T07:30:06Z |
## Description
<!-- Describe your changes in detail -->
This adds batch encrypt/decrypt support for Merchant Connector account create/fetch/update
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6205
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create MerchantConnector Account
```bash
{
"connector_type": "fiz_operations",
"connector_name": "checkout_test",
"connector_label": "checkout_test_US_default",
"merchant_connector_id": "mca_1nx2lpMSrHoJZ0Xiw3CM",
"profile_id": "pro_1tS3symGpqUT5zGglYyI",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "pk*******************************u5"
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sofort",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "giropay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"google_pay": {
"merchant_info": {
"merchant_id": "sundari",
"merchant_name": "gpay"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "checkoutltd",
"gateway_merchant_id": "pk_sbox_ivbndwrrb35t67wrveqic347ii4"
}
}
}
]
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null,
"connector_wallets_details": {
"apple_pay_combined": {
"manual": {
"payment_request_data": {
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
],
"label": "applepay"
},
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"display_name": "checkoutapple",
"initiative": "web",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": null
}
}
}
}
}
```
2. Update MerchantConnectorAccount
```bash
curl --location 'http://localhost:8080/account/merchant_123_1727938790/connectors/mca_1nx2lpMSrHoJZ0Xiw3CM' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": ""
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_countries": {
"type": "disable_only",
"list": [
"US",
"GB",
"IN"
]
},
"accepted_currencies": {
"type": "enable_only",
"list": [
"USD",
"GBP",
"INR"
]
}
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_countries": {
"type": "enable_only",
"list": [
"US",
"GB",
"IN"
]
},
"accepted_currencies": {
"type": "disable_only",
"list": [
"USD",
"GBP",
"INR"
]
}
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245"
},
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret"
},
"business_country": "US",
"business_label": "default"
}'
```
3. Sanity test on `/payments`
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \
--data-raw '{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "HScustomer1234",
"email": "p143@example.com",
"amount_to_capture": 600,
"description": "Its my first payment request",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"name": "Preetam",
"phone": "999999999",
"setup_future_usage": "off_session",
"phone_country_code": "+65",
"authentication_type": "three_ds",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"connector_metadata": {
"noon": {
"order_category": "applepay"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "preetam",
"last_name": "revankar"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
],
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
``` | a3c2694943a985d27b5bc8b0371884d17a6ca34d |
1. Create MerchantConnector Account
```bash
{
"connector_type": "fiz_operations",
"connector_name": "checkout_test",
"connector_label": "checkout_test_US_default",
"merchant_connector_id": "mca_1nx2lpMSrHoJZ0Xiw3CM",
"profile_id": "pro_1tS3symGpqUT5zGglYyI",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "pk*******************************u5"
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sofort",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "giropay",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": null,
"maximum_amount": null,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"google_pay": {
"merchant_info": {
"merchant_id": "sundari",
"merchant_name": "gpay"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "checkoutltd",
"gateway_merchant_id": "pk_sbox_ivbndwrrb35t67wrveqic347ii4"
}
}
}
]
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null,
"connector_wallets_details": {
"apple_pay_combined": {
"manual": {
"payment_request_data": {
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
],
"label": "applepay"
},
"merchant_identifier": "merchant.com.hyperswitch.checkout",
"display_name": "checkoutapple",
"initiative": "web",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": null
}
}
}
}
}
```
2. Update MerchantConnectorAccount
```bash
curl --location 'http://localhost:8080/account/merchant_123_1727938790/connectors/mca_1nx2lpMSrHoJZ0Xiw3CM' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": ""
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_countries": {
"type": "disable_only",
"list": [
"US",
"GB",
"IN"
]
},
"accepted_currencies": {
"type": "enable_only",
"list": [
"USD",
"GBP",
"INR"
]
}
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"accepted_countries": {
"type": "enable_only",
"list": [
"US",
"GB",
"IN"
]
},
"accepted_currencies": {
"type": "disable_only",
"list": [
"USD",
"GBP",
"INR"
]
}
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245"
},
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret"
},
"business_country": "US",
"business_label": "default"
}'
```
3. Sanity test on `/payments`
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \
--data-raw '{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "HScustomer1234",
"email": "p143@example.com",
"amount_to_capture": 600,
"description": "Its my first payment request",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"name": "Preetam",
"phone": "999999999",
"setup_future_usage": "off_session",
"phone_country_code": "+65",
"authentication_type": "three_ds",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"connector_metadata": {
"noon": {
"order_category": "applepay"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "preetam",
"last_name": "revankar"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
],
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
| [
"crates/hyperswitch_domain_models/src/merchant_connector_account.rs",
"crates/router/src/core/admin.rs",
"crates/router/src/core/payments/helpers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5961 | Bug: [REFACTOR]: [PAYU] Add amount conversion framework to Payu
### :memo: Feature Description
Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows.
Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application.
### :hammer: Possible Implementation
- For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly.
- Connectors should invoke the `convert` function to receive the amount in their required format.
- Refer to the [connector documentation](https://docs.payu.in/reference/refund_transaction_api) to determine the required amount format for each connector.
- You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context.
🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/`
### :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)
### :package: Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
### :sparkles: Are you willing to submit a PR?
| diff --git a/crates/hyperswitch_connectors/src/connectors/payu.rs b/crates/hyperswitch_connectors/src/connectors/payu.rs
index 05f983b8fbb..ad2479f19e4 100644
--- a/crates/hyperswitch_connectors/src/connectors/payu.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payu.rs
@@ -6,6 +6,7 @@ use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
@@ -43,11 +44,22 @@ use transformers as payu;
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
+ utils,
utils::construct_not_supported_error_report,
};
-#[derive(Debug, Clone)]
-pub struct Payu;
+#[derive(Clone)]
+pub struct Payu {
+ amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
+}
+
+impl Payu {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &MinorUnitForConnector,
+ }
+ }
+}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payu
where
@@ -538,7 +550,15 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = payu::PayuPaymentsRequest::try_from(req)?;
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = payu::PayuRouterData::try_from((amount, req))?;
+
+ let connector_req = payu::PayuPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -625,7 +645,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payu {
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = payu::PayuRefundRequest::try_from(req)?;
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = payu::PayuRouterData::try_from((amount, req))?;
+ let connector_req = payu::PayuRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
index 4ebc09a0023..9bdb52de4f0 100644
--- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
@@ -3,6 +3,7 @@ use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
pii::{Email, IpAddress},
+ types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
@@ -24,12 +25,28 @@ use crate::{
const WALLET_IDENTIFIER: &str = "PBL";
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize)]
+pub struct PayuRouterData<T> {
+ pub amount: MinorUnit,
+ pub router_data: T,
+}
+
+impl<T> TryFrom<(MinorUnit, T)> for PayuRouterData<T> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
+#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsRequest {
customer_ip: Secret<String, IpAddress>,
merchant_pos_id: Secret<String>,
- total_amount: i64,
+ total_amount: MinorUnit,
currency_code: enums::Currency,
description: String,
pay_methods: PayuPaymentMethod,
@@ -77,11 +94,13 @@ pub enum PayuWalletCode {
Jp,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
+impl TryFrom<&PayuRouterData<&types::PaymentsAuthorizeRouterData>> for PayuPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let auth_type = PayuAuthType::try_from(&item.connector_auth_type)?;
- let payment_method = match item.request.payment_method_data.clone() {
+ fn try_from(
+ item: &PayuRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let auth_type = PayuAuthType::try_from(&item.router_data.connector_auth_type)?;
+ let payment_method = match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod {
pay_method: PayuPaymentMethodData::Card(PayuCard::Card {
number: ccard.card_number,
@@ -119,7 +138,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
"Unknown payment method".to_string(),
)),
}?;
- let browser_info = item.request.browser_info.clone().ok_or(
+ let browser_info = item.router_data.request.browser_info.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "browser_info",
},
@@ -134,10 +153,10 @@ 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(
+ ext_order_id: Some(item.router_data.connector_request_reference_id.clone()),
+ total_amount: item.amount.to_owned(),
+ currency_code: item.router_data.request.currency,
+ description: item.router_data.description.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "item.description",
},
@@ -488,10 +507,10 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsRe
}
}
-#[derive(Default, Debug, Eq, PartialEq, Serialize)]
+#[derive(Default, Debug, Serialize)]
pub struct PayuRefundRequestData {
description: String,
- amount: Option<i64>,
+ amount: Option<MinorUnit>,
}
#[derive(Default, Debug, Serialize)]
@@ -499,12 +518,12 @@ pub struct PayuRefundRequest {
refund: PayuRefundRequestData,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for PayuRefundRequest {
+impl<F> TryFrom<&PayuRouterData<&types::RefundsRouterData<F>>> for PayuRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(item: &PayuRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
refund: PayuRefundRequestData {
- description: item.request.reason.clone().ok_or(
+ description: item.router_data.request.reason.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "item.request.reason",
},
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index b85ae5bfab2..a3046213272 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -458,7 +458,7 @@ impl ConnectorData {
enums::Connector::Payone => {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
- enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(&connector::Payu))),
+ enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs
index b0e5e9ec6a1..9bb3785bbd6 100644
--- a/crates/router/tests/connectors/payu.rs
+++ b/crates/router/tests/connectors/payu.rs
@@ -11,7 +11,7 @@ impl Connector for Payu {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Payu;
utils::construct_connector_data_old(
- Box::new(&Payu),
+ Box::new(Payu::new()),
types::Connector::Payu,
types::api::GetToken::Connector,
None,
| 2024-10-02T14:12:09Z |
## Description
This PR adds amount conversion framework to payu, for sending to connector.
fixes #5961
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
--> | a3ea62f88524a360b666cacfbc1cf239f6be8797 | [
"crates/hyperswitch_connectors/src/connectors/payu.rs",
"crates/hyperswitch_connectors/src/connectors/payu/transformers.rs",
"crates/router/src/types/api.rs",
"crates/router/tests/connectors/payu.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-5913 | Bug: [CYPRESS_FRAMEWORK] Re-use config update commands
**Description:**
Cypress is the testing framework that Hyperswitch uses to run automated tests. Having good grip on Javascript to work on Cypress is a must.
Cypress makes use of custom [commands](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/commands.js) to make requests and parse responses instead of having the exchange put in a spec file. This increases the code redundancy. Custom commands are versatile that helps in reducing command duplication. These commands should be generic and should be capable of handling multiple requests of same / similar type.
**The problem:**
Currently, there exist `3` implementations that makes update config request for different purposes:
- [autoRetryConfig](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2229-L2255)
- [setMaxAutoRetries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2257-L2282)
- [stepUp](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2312-L2334)
These are called by [Retries](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js) tests under Routing specs.
**Getting started:**
Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress.
In short:
```sh
cd cypress-tests
npm ci
```
**Possible implementation:**
Refactor config update `context`s in the spec file (for example: [Update max auto retries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L102-L108), [Enable auto retries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L46-L48), [Step up](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L482C10-L483C14)) and pass as all the necessary data into the new unified command in [commands](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/commands.js)
**Additional info:**
- Language: Javascript
- Difficulty: Easy
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | 2024-10-02T12:55:09Z |
## Description
This PR refactors the existing Cypress commands used for configuration updates (autoRetryConfig, setMaxAutoRetries, and stepUp) into a single unified command cy.updateConfig. The refactor helps reduce redundancy in the codebase by consolidating multiple similar implementations into one versatile command that can handle configuration changes for auto retries, max retries, and step-up flows.
## Key Changes
-Combined autoRetryConfig, setMaxAutoRetries, and stepUp into the cy.updateConfig command.
-Updated the Retries.cy.js test cases to use the new unified command for disabling/enabling auto retries and step-up configurations.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## Motivation and Context
The refactor was necessary to reduce code duplication and improve maintainability. By creating a unified command, we ensure that future changes to configuration updates are centralized in one place, making the code easier to manage and extend.
## How did you test it?
Tested manually and with cypress command. | 19a8474d8731ed7149b541f02ad237e30c4c9f24 | Tested manually and with cypress command.
| [] | ||
juspay/hyperswitch | juspay__hyperswitch-5917 | Bug: [FIX] Add Limit Parameter to User Role List for Org Function
### Feature Description
Description: The function [generic_user_roles_list_for_org_and_extra](https://github.com/juspay/hyperswitch/blob/a94cf25bb6eb40fafc5327aceffac8292b47b001/crates/diesel_models/src/query/user_role.rs#L270) currently fetches all roles for a give organisation and additional parameters. To improve performance and allow better control over data retrieval, we need to add a limit parameter to restrict the number of results returned.
```
pub async fn generic_user_roles_list_for_org_and_extra(
conn: &PgPooledConn,
user_id: Option<String>,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
version: Option<UserRoleVersion>,
) -> StorageResult<Vec<Self>>
```
Task:
- Modify the existing function generic_user_roles_list_for_org_and_extra to include an optional limit parameter (Option<u32>).
- Pass this limit parameter down to the database query to restrict the number of user roles returned.
- Ensure the limit parameter is optional, and when it's not provided, the function should return all results as it currently does.
### Possible Implementation
- Add an additional parameter limit: `Option<type>` to the function signature of `generic_user_roles_list_for_org_and_extra`
- Modify the query logic to apply the limit if it is provided.
- Ensure the modified function still works with existing code that doesn't use the limit parameter. ( For older implementations, where this function is getting called, pass limit as `None` so that it doesn't change expected behaviour)
Additional Context: This change is analogous to the `generic_user_roles_list_for_user` function, which already includes a limit parameter. You can refer to that function’s implementation for guidance.
### How to Test
For testing, we can check where this `generic_user_roles_list_for_user` is used, currently this function is invoked from db function `list_user_roles_by_user_id` and this function is getting called from many core function, like `list_merchants_for_user_in_org` , `list_orgs_for_user`.
We can hit `user/list/merchants` api to invoke this `list_merchants_for_user_in_org` core function:
Signup:
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"email": "email1@gmail.com",
"password": "Pass@123"
}'
```
Response:
```
{
"token": "JWT",
"token_type": "totp"
}
```
We will get intermediate token for setting up 2FA, it is skippable:
Skip 2FA, we will be getting a login token:
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: Bearer Intermediate_Token'
```
```
{
"token": "JWT",
"token_type": "user_info"
}
```
It depicts successful signup, default one merchant_id has been created. (Baisically one org, with one merchant and one profile)
Now we can call `list/merchant`:
```
curl --location 'http://localhost:8080/user/list/merchant' \
--header 'Authorization: Bearer LOGIN_JWT'
```
Response:
```
[
{
"merchant_id": "merchant_test"
"merchant_name": null
}
]
```
We can create more merchant accounts:
```
curl --location 'http://localhost:8080/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer LoginJWT' \
--data '{
"company_name": "hyperswitch"
}'
```
And if we try got get list it now, it will show more merchant_ids in list. Limit parameter in the function that controls how much data we need for our use case, say, sometimes we only want to get first one from list, we can just pass limit one instead of fetching whole list.
Acceptance Criteria:
- The function should accept an optional limit parameter.
- When a limit is provided, the number of results returned by the query should not exceed the limit.
- Tests the behaviour with and without the limit parameter.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 5ef09715211..2496d22447e 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -258,6 +258,7 @@ impl UserRole {
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
version: Option<UserRoleVersion>,
+ limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::org_id.eq(org_id))
@@ -279,6 +280,10 @@ impl UserRole {
query = query.filter(dsl::version.eq(version));
}
+ if let Some(limit) = limit {
+ query = query.limit(limit.into());
+ }
+
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 2cd715ac357..1d188168e5c 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -614,6 +614,7 @@ pub async fn list_users_in_lineage(
merchant_id: None,
profile_id: None,
version: None,
+ limit: None,
},
request.entity_type,
)
@@ -628,6 +629,7 @@ pub async fn list_users_in_lineage(
merchant_id: Some(&user_from_token.merchant_id),
profile_id: None,
version: None,
+ limit: None,
},
request.entity_type,
)
@@ -646,6 +648,7 @@ pub async fn list_users_in_lineage(
merchant_id: Some(&user_from_token.merchant_id),
profile_id: Some(profile_id),
version: None,
+ limit: None,
},
request.entity_type,
)
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index b589d375975..1fa70afa73f 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -19,6 +19,7 @@ pub struct ListUserRolesByOrgIdPayload<'a> {
pub merchant_id: Option<&'a id_type::MerchantId>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub version: Option<enums::UserRoleVersion>,
+ pub limit: Option<u32>,
}
pub struct ListUserRolesByUserIdPayload<'a> {
@@ -193,6 +194,7 @@ impl UserRoleInterface for Store {
payload.merchant_id.cloned(),
payload.profile_id.cloned(),
payload.version,
+ payload.limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
| 2024-10-01T16:00:18Z |
## Description
<!-- Describe your changes in detail -->
This PR adds the `limit` parameter to the `generic_user_roles_list_for_org_and_extra` function.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #5917
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
When having 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb in:
```shell
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
yields
```
[{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}]
```
**Outdated** by 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb:
Both _queries_
```shell
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=10' \
-H 'authorization: Bearer JWT' \
```
yield:
```
[{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}]
```
The _query_
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=0' \
-H 'authorization: Bearer JWT' \
```
yields:
```
[]
```
The _query_
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=-10' \
-H 'authorization: Bearer JWT' \
```
errors with:
```
Query deserialize error: invalid digit found in string
``` | 19a8474d8731ed7149b541f02ad237e30c4c9f24 |
When having 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb in:
```shell
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
yields
```
[{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}]
```
**Outdated** by 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb:
Both _queries_
```shell
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=10' \
-H 'authorization: Bearer JWT' \
```
yield:
```
[{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}]
```
The _query_
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=0' \
-H 'authorization: Bearer JWT' \
```
yields:
```
[]
```
The _query_
```shell
curl 'http://localhost:8080/user/user/v2/list?limit=-10' \
-H 'authorization: Bearer JWT' \
```
errors with:
```
Query deserialize error: invalid digit found in string
```
| [
"crates/diesel_models/src/query/user_role.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/db/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5915 | Bug: [CYPRESS_FRAMEWORK] Verify URL after redirection
**Description:**
Cypress is the testing framework that Hyperswitch uses to run automated tests as it helps test both backend as well as frontend in a single shot that includes redirection flows like `3ds` and `bank redirect`.
Redirection tests in Cypress at present do not validate the end URL. This can lead to unnecessary complication and false positives when running tests that involve redirection say, 3ds tests, bank redirect tests, bank transfer tests and etc.,
The task is to refactor the [verifyReturnUrl function](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/redirectionHandler.js#L397-L414) in [redirection handler](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/redirectionHandler.js) to validate the URL
**Getting started:**
Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress.
**Possible implementation:**
- Refactor the [verifyReturnUrl](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/redirectionHandler.js#L397-L414) function in [redirection handler](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/redirectionHandler.js) support file
- Verify that `redirection_url` has status that equates to either succeeded or processing. Fail the test otherwise
Example:
Below is the `redirection_url` that has the terminal status of the payment after redirection. `verifyReturnUrl` function should parse `redirection_url` and validate the status.
redirection_url: `https://duckduckgo.com/?payment_id=pay_K29MmxZKI9rDhhSY7sb8&status=succeeded`
**Additional info:**
- Language: Javascript
- Difficulty: Easy
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | 2024-10-01T10:33:37Z |
## Description
This PR refactors the verifyReturnUrl function to validate the redirection_url and ensure that the payment status is either succeeded or processing. If the status is invalid, the test will now fail, preventing false positives in redirection tests like 3DS or bank redirects.
###Key Changes:
- Parse the redirection_url query string to extract the status parameter.
- Validate the status against the allowed values (succeeded or processing).
- Fail the test if the status is not one of the expected values.
- Maintain the existing redirection validation process (e.g., origin matching).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## Motivation and Context
This change improves the reliability of Cypress redirection tests by ensuring that the final redirection URL reflects a valid payment status, preventing false positives and ensuring tests behave as expected for flows like 3DS and bank redirects.
## How did you test it?
Ran against Integ environment for Stripe:
<img width="555" alt="image" src="https://github.com/user-attachments/assets/0dc3fb11-4f2c-4731-9f23-8a3a0dc9ab94" />
when the validation fails, below is the kind of error we get:
<img width="551" alt="image" src="https://github.com/user-attachments/assets/e15418f2-ad97-4502-b342-a220c2d7fc7b" /> | d8d8c400bbda49b9a0cd5edbe37e929ae6d38eb4 | Ran against Integ environment for Stripe:
<img width="555" alt="image" src="https://github.com/user-attachments/assets/0dc3fb11-4f2c-4731-9f23-8a3a0dc9ab94" />
when the validation fails, below is the kind of error we get:
<img width="551" alt="image" src="https://github.com/user-attachments/assets/e15418f2-ad97-4502-b342-a220c2d7fc7b" />
| [] | ||
juspay/hyperswitch | juspay__hyperswitch-6186 | Bug: feat(users): Allow multiple org_admins in single org
Currently, there can only be a single org_admin in a org, and that is the person who signed up.
All the other users will be either merchant level or profile level.
Since, there can be a usecase where a org needs multiple org admins, we should allow multiple org_admins. | diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 1cd25e54cb3..f4142842e21 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -5,7 +5,6 @@ use diesel::{
BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
-use router_env::logger;
use crate::{
enums::{UserRoleVersion, UserStatus},
@@ -23,21 +22,6 @@ impl UserRoleNew {
}
impl UserRole {
- pub async fn insert_multiple_user_roles(
- conn: &PgPooledConn,
- user_roles: Vec<UserRoleNew>,
- ) -> StorageResult<Vec<Self>> {
- let query = diesel::insert_into(<Self>::table()).values(user_roles);
-
- logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
-
- query
- .get_results_async(conn)
- .await
- .change_context(errors::DatabaseError::Others)
- .attach_printable("Error while inserting user_roles")
- }
-
pub async fn find_by_user_id(
conn: &PgPooledConn,
user_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f36ecc18116..a1a78656de1 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -67,7 +67,6 @@ pub async fn signup_with_merchant_id(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -146,7 +145,6 @@ pub async fn signup_token_only_flow(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -247,7 +245,6 @@ pub async fn connect_account(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -657,7 +654,7 @@ async fn handle_existing_user_invitation(
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
- .insert_in_v1_and_v2(state)
+ .insert_in_v2(state)
.await?
}
EntityType::Profile => {
@@ -767,14 +764,21 @@ async fn handle_new_user_invitation(
};
let _user_role = match role_info.get_entity_type() {
- EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => {
+ user_role
+ .add_entity(domain::OrganizationLevel {
+ org_id: user_from_token.org_id.clone(),
+ })
+ .insert_in_v2(state)
+ .await?
+ }
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
- .insert_in_v1_and_v2(state)
+ .insert_in_v2(state)
.await?
}
EntityType::Profile => {
@@ -1128,7 +1132,7 @@ pub async fn create_internal_user(
org_id: internal_merchant.organization_id,
merchant_id: internal_merchant_id,
})
- .insert_in_v1_and_v2(&state)
+ .insert_in_v2(&state)
.await
.change_context(UserErrors::InternalServerError)?;
@@ -1257,28 +1261,11 @@ pub async fn create_merchant_account(
) -> UserResponse<()> {
let user_from_db = user_from_token.get_user_from_db(&state).await?;
- let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?;
- let new_merchant = new_user.get_new_merchant();
+ let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?;
new_merchant
.create_new_merchant_and_insert_in_db(state.to_owned())
.await?;
- let role_insertion_res = new_user
- .insert_org_level_user_role_in_db(
- state.clone(),
- common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- UserStatus::Active,
- Some(UserRoleVersion::V1),
- )
- .await;
- if let Err(e) = role_insertion_res {
- let _ = state
- .store
- .delete_merchant_account_by_merchant_id(&new_merchant.get_merchant_id())
- .await;
- return Err(e);
- }
-
Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index de10b70f507..11082a65a49 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -37,10 +37,7 @@ use super::{
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
- user_role::{
- InsertUserRolePayload, ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload,
- UserRoleInterface,
- },
+ user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
@@ -3018,8 +3015,8 @@ impl RedisConnInterface for KafkaStore {
impl UserRoleInterface for KafkaStore {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store.insert_user_role(user_role).await
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d511010e6b5..e9e7cafa3fd 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -13,21 +13,6 @@ use crate::{
services::Store,
};
-pub enum InsertUserRolePayload {
- OnlyV1(storage::UserRoleNew),
- OnlyV2(storage::UserRoleNew),
- V1AndV2(Box<[storage::UserRoleNew; 2]>),
-}
-
-impl InsertUserRolePayload {
- fn convert_to_vec(self) -> Vec<storage::UserRoleNew> {
- match self {
- Self::OnlyV1(user_role) | Self::OnlyV2(user_role) => vec![user_role],
- Self::V1AndV2(user_roles) => user_roles.to_vec(),
- }
- }
-}
-
pub struct ListUserRolesByOrgIdPayload<'a> {
pub user_id: Option<&'a String>,
pub org_id: &'a id_type::OrganizationId,
@@ -51,8 +36,8 @@ pub struct ListUserRolesByUserIdPayload<'a> {
pub trait UserRoleInterface {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn find_user_role_by_user_id(
&self,
@@ -123,11 +108,12 @@ impl UserRoleInterface for Store {
#[instrument(skip_all)]
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::insert_multiple_user_roles(&conn, user_role.convert_to_vec())
+ user_role
+ .insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -295,44 +281,38 @@ impl UserRoleInterface for Store {
impl UserRoleInterface for MockDb {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut db_user_roles = self.user_roles.lock().await;
- user_role
- .convert_to_vec()
- .into_iter()
- .map(|user_role| {
- if db_user_roles
- .iter()
- .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
- {
- Err(errors::StorageError::DuplicateValue {
- entity: "user_id",
- key: None,
- })?
- }
- let user_role = storage::UserRole {
- id: i32::try_from(db_user_roles.len())
- .change_context(errors::StorageError::MockDbError)?,
- user_id: user_role.user_id,
- merchant_id: user_role.merchant_id,
- role_id: user_role.role_id,
- status: user_role.status,
- created_by: user_role.created_by,
- created_at: user_role.created_at,
- last_modified: user_role.last_modified,
- last_modified_by: user_role.last_modified_by,
- org_id: user_role.org_id,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: enums::UserRoleVersion::V1,
- };
- db_user_roles.push(user_role.clone());
- Ok(user_role)
- })
- .collect::<Result<Vec<_>, _>>()
+ if db_user_roles
+ .iter()
+ .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_id",
+ key: None,
+ })?
+ }
+ let user_role = storage::UserRole {
+ id: i32::try_from(db_user_roles.len())
+ .change_context(errors::StorageError::MockDbError)?,
+ user_id: user_role.user_id,
+ merchant_id: user_role.merchant_id,
+ role_id: user_role.role_id,
+ status: user_role.status,
+ created_by: user_role.created_by,
+ created_at: user_role.created_at,
+ last_modified: user_role.last_modified,
+ last_modified_by: user_role.last_modified_by,
+ org_id: user_role.org_id,
+ profile_id: None,
+ entity_id: None,
+ entity_type: None,
+ version: enums::UserRoleVersion::V1,
+ };
+ db_user_roles.push(user_role.clone());
+ Ok(user_role)
}
async fn find_user_role_by_user_id(
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index b271abd1eff..33a1d5f53ca 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -83,9 +83,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Organization,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
is_internal: false,
},
);
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 19d682aeef1..a664fc84978 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -30,7 +30,7 @@ use crate::{
admin,
errors::{UserErrors, UserResult},
},
- db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
+ db::GlobalStorageInterface,
routes::SessionState,
services::{self, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
@@ -661,26 +661,17 @@ impl NewUser {
state: SessionState,
role_id: String,
user_status: UserStatus,
- version: Option<UserRoleVersion>,
) -> UserResult<UserRole> {
let org_id = self
.get_new_merchant()
.get_new_organization()
.get_organization_id();
- let merchant_id = self.get_new_merchant().get_merchant_id();
let org_user_role = self
.get_no_level_user_role(role_id, user_status)
- .add_entity(OrganizationLevel {
- org_id,
- merchant_id,
- });
-
- match version {
- Some(UserRoleVersion::V1) => org_user_role.insert_in_v1(&state).await,
- Some(UserRoleVersion::V2) => org_user_role.insert_in_v2(&state).await,
- None => org_user_role.insert_in_v1_and_v2(&state).await,
- }
+ .add_entity(OrganizationLevel { org_id });
+
+ org_user_role.insert_in_v2(&state).await
}
}
@@ -1119,8 +1110,6 @@ pub struct NoLevel;
#[derive(Clone)]
pub struct OrganizationLevel {
pub org_id: id_type::OrganizationId,
- // Keeping this to allow insertion of org_admins in V1
- pub merchant_id: id_type::MerchantId,
}
#[derive(Clone)]
@@ -1174,32 +1163,46 @@ pub struct EntityInfo {
entity_type: EntityType,
}
-impl<E> NewUserRole<E>
-where
- E: Clone,
-{
- fn convert_to_new_v1_role(
- self,
- org_id: id_type::OrganizationId,
- merchant_id: id_type::MerchantId,
- ) -> UserRoleNew {
- UserRoleNew {
- user_id: self.user_id,
- role_id: self.role_id,
- status: self.status,
- created_by: self.created_by,
- last_modified_by: self.last_modified_by,
- created_at: self.created_at,
- last_modified: self.last_modified,
- org_id: Some(org_id),
- merchant_id: Some(merchant_id),
+impl From<OrganizationLevel> for EntityInfo {
+ fn from(value: OrganizationLevel) -> Self {
+ Self {
+ entity_id: value.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ org_id: value.org_id,
+ merchant_id: None,
+ profile_id: None,
+ }
+ }
+}
+
+impl From<MerchantLevel> for EntityInfo {
+ fn from(value: MerchantLevel) -> Self {
+ Self {
+ entity_id: value.merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Merchant,
+ org_id: value.org_id,
profile_id: None,
- entity_id: None,
- entity_type: None,
- version: UserRoleVersion::V1,
+ merchant_id: Some(value.merchant_id),
}
}
+}
+impl From<ProfileLevel> for EntityInfo {
+ fn from(value: ProfileLevel) -> Self {
+ Self {
+ entity_id: value.profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ org_id: value.org_id,
+ merchant_id: Some(value.merchant_id),
+ profile_id: Some(value.profile_id),
+ }
+ }
+}
+
+impl<E> NewUserRole<E>
+where
+ E: Clone + Into<EntityInfo>,
+{
fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {
UserRoleNew {
user_id: self.user_id,
@@ -1218,116 +1221,15 @@ where
}
}
- async fn insert_v1_and_v2_in_db_and_get_v2(
- state: &SessionState,
- v1_role: UserRoleNew,
- v2_role: UserRoleNew,
- ) -> UserResult<UserRole> {
- let inserted_roles = state
- .store
- .insert_user_role(InsertUserRolePayload::V1AndV2(Box::new([v1_role, v2_role])))
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- inserted_roles
- .into_iter()
- .find(|role| role.version == UserRoleVersion::V2)
- .ok_or(report!(UserErrors::InternalServerError))
- }
-}
-
-impl NewUserRole<OrganizationLevel> {
- pub async fn insert_in_v1(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
-
- state
- .store
- .insert_user_role(InsertUserRolePayload::OnlyV1(new_v1_role))
- .await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
- }
-
pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
let entity = self.entity.clone();
- let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: None,
- profile_id: None,
- entity_id: entity.org_id.get_string_repr().to_owned(),
- entity_type: EntityType::Organization,
- });
- state
- .store
- .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
- .await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
- }
-
- pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
+ let new_v2_role = self.convert_to_new_v2_role(entity.into());
- let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: None,
- profile_id: None,
- entity_id: entity.org_id.get_string_repr().to_owned(),
- entity_type: EntityType::Organization,
- });
-
- Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
- }
-}
-
-impl NewUserRole<MerchantLevel> {
- pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
-
- let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: Some(entity.merchant_id.clone()),
- profile_id: None,
- entity_id: entity.merchant_id.get_string_repr().to_owned(),
- entity_type: EntityType::Merchant,
- });
-
- Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
- }
-}
-
-impl NewUserRole<ProfileLevel> {
- pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: Some(entity.merchant_id.clone()),
- profile_id: Some(entity.profile_id.clone()),
- entity_id: entity.profile_id.get_string_repr().to_owned(),
- entity_type: EntityType::Profile,
- });
state
.store
- .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
+ .insert_user_role(new_v2_role)
.await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
+ .change_context(UserErrors::InternalServerError)
}
}
| 2024-10-01T10:27:33Z |
## Description
<!-- Describe your changes in detail -->
Currently we are inserting user_roles in v1 version and v2 version. Since we have completely moved the APIs to support v2, we don't have to insert v1 anymore.
Allow inviting, updating and deleting org_admins.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6184
Closes #6186
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the following APIs will insert only v2 user_roles from now on.
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"name" : "name",
"email" : "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
},
{
"email": "email 2",
"name": "name",
"role_id": "merchant_admin"
}
]'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"company_name": "Juspay"
}'
```
You will now be able to invite org_admin
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "org_admin"
}
]'
``` | 4dae29221f2d24a0f4299e641cfe22ab705fae25 |
All the following APIs will insert only v2 user_roles from now on.
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"name" : "name",
"email" : "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
},
{
"email": "email 2",
"name": "name",
"role_id": "merchant_admin"
}
]'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"company_name": "Juspay"
}'
```
You will now be able to invite org_admin
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "org_admin"
}
]'
```
| [
"crates/diesel_models/src/query/user_role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user_role.rs",
"crates/router/src/services/authorization/roles/predefined_roles.rs",
"crates/router/src/types/domain/user.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6184 | Bug: refactor(users): Remove v1 insertions for user_roles
Currently, we are inserting user_roles in v1 version and v2 version.
Since we moved all the APIs to work with v2 data, we can stop inserting v1 data.
This will also help in migrating v1 data to v2. | diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 1cd25e54cb3..f4142842e21 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -5,7 +5,6 @@ use diesel::{
BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
-use router_env::logger;
use crate::{
enums::{UserRoleVersion, UserStatus},
@@ -23,21 +22,6 @@ impl UserRoleNew {
}
impl UserRole {
- pub async fn insert_multiple_user_roles(
- conn: &PgPooledConn,
- user_roles: Vec<UserRoleNew>,
- ) -> StorageResult<Vec<Self>> {
- let query = diesel::insert_into(<Self>::table()).values(user_roles);
-
- logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
-
- query
- .get_results_async(conn)
- .await
- .change_context(errors::DatabaseError::Others)
- .attach_printable("Error while inserting user_roles")
- }
-
pub async fn find_by_user_id(
conn: &PgPooledConn,
user_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f36ecc18116..a1a78656de1 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -67,7 +67,6 @@ pub async fn signup_with_merchant_id(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -146,7 +145,6 @@ pub async fn signup_token_only_flow(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -247,7 +245,6 @@ pub async fn connect_account(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
- None,
)
.await?;
@@ -657,7 +654,7 @@ async fn handle_existing_user_invitation(
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
- .insert_in_v1_and_v2(state)
+ .insert_in_v2(state)
.await?
}
EntityType::Profile => {
@@ -767,14 +764,21 @@ async fn handle_new_user_invitation(
};
let _user_role = match role_info.get_entity_type() {
- EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
+ EntityType::Organization => {
+ user_role
+ .add_entity(domain::OrganizationLevel {
+ org_id: user_from_token.org_id.clone(),
+ })
+ .insert_in_v2(state)
+ .await?
+ }
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
- .insert_in_v1_and_v2(state)
+ .insert_in_v2(state)
.await?
}
EntityType::Profile => {
@@ -1128,7 +1132,7 @@ pub async fn create_internal_user(
org_id: internal_merchant.organization_id,
merchant_id: internal_merchant_id,
})
- .insert_in_v1_and_v2(&state)
+ .insert_in_v2(&state)
.await
.change_context(UserErrors::InternalServerError)?;
@@ -1257,28 +1261,11 @@ pub async fn create_merchant_account(
) -> UserResponse<()> {
let user_from_db = user_from_token.get_user_from_db(&state).await?;
- let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?;
- let new_merchant = new_user.get_new_merchant();
+ let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?;
new_merchant
.create_new_merchant_and_insert_in_db(state.to_owned())
.await?;
- let role_insertion_res = new_user
- .insert_org_level_user_role_in_db(
- state.clone(),
- common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- UserStatus::Active,
- Some(UserRoleVersion::V1),
- )
- .await;
- if let Err(e) = role_insertion_res {
- let _ = state
- .store
- .delete_merchant_account_by_merchant_id(&new_merchant.get_merchant_id())
- .await;
- return Err(e);
- }
-
Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index de10b70f507..11082a65a49 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -37,10 +37,7 @@ use super::{
user::{sample_data::BatchSampleDataInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
- user_role::{
- InsertUserRolePayload, ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload,
- UserRoleInterface,
- },
+ user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
@@ -3018,8 +3015,8 @@ impl RedisConnInterface for KafkaStore {
impl UserRoleInterface for KafkaStore {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store.insert_user_role(user_role).await
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d511010e6b5..e9e7cafa3fd 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -13,21 +13,6 @@ use crate::{
services::Store,
};
-pub enum InsertUserRolePayload {
- OnlyV1(storage::UserRoleNew),
- OnlyV2(storage::UserRoleNew),
- V1AndV2(Box<[storage::UserRoleNew; 2]>),
-}
-
-impl InsertUserRolePayload {
- fn convert_to_vec(self) -> Vec<storage::UserRoleNew> {
- match self {
- Self::OnlyV1(user_role) | Self::OnlyV2(user_role) => vec![user_role],
- Self::V1AndV2(user_roles) => user_roles.to_vec(),
- }
- }
-}
-
pub struct ListUserRolesByOrgIdPayload<'a> {
pub user_id: Option<&'a String>,
pub org_id: &'a id_type::OrganizationId,
@@ -51,8 +36,8 @@ pub struct ListUserRolesByUserIdPayload<'a> {
pub trait UserRoleInterface {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn find_user_role_by_user_id(
&self,
@@ -123,11 +108,12 @@ impl UserRoleInterface for Store {
#[instrument(skip_all)]
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::insert_multiple_user_roles(&conn, user_role.convert_to_vec())
+ user_role
+ .insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -295,44 +281,38 @@ impl UserRoleInterface for Store {
impl UserRoleInterface for MockDb {
async fn insert_user_role(
&self,
- user_role: InsertUserRolePayload,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
+ user_role: storage::UserRoleNew,
+ ) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut db_user_roles = self.user_roles.lock().await;
- user_role
- .convert_to_vec()
- .into_iter()
- .map(|user_role| {
- if db_user_roles
- .iter()
- .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
- {
- Err(errors::StorageError::DuplicateValue {
- entity: "user_id",
- key: None,
- })?
- }
- let user_role = storage::UserRole {
- id: i32::try_from(db_user_roles.len())
- .change_context(errors::StorageError::MockDbError)?,
- user_id: user_role.user_id,
- merchant_id: user_role.merchant_id,
- role_id: user_role.role_id,
- status: user_role.status,
- created_by: user_role.created_by,
- created_at: user_role.created_at,
- last_modified: user_role.last_modified,
- last_modified_by: user_role.last_modified_by,
- org_id: user_role.org_id,
- profile_id: None,
- entity_id: None,
- entity_type: None,
- version: enums::UserRoleVersion::V1,
- };
- db_user_roles.push(user_role.clone());
- Ok(user_role)
- })
- .collect::<Result<Vec<_>, _>>()
+ if db_user_roles
+ .iter()
+ .any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_id",
+ key: None,
+ })?
+ }
+ let user_role = storage::UserRole {
+ id: i32::try_from(db_user_roles.len())
+ .change_context(errors::StorageError::MockDbError)?,
+ user_id: user_role.user_id,
+ merchant_id: user_role.merchant_id,
+ role_id: user_role.role_id,
+ status: user_role.status,
+ created_by: user_role.created_by,
+ created_at: user_role.created_at,
+ last_modified: user_role.last_modified,
+ last_modified_by: user_role.last_modified_by,
+ org_id: user_role.org_id,
+ profile_id: None,
+ entity_id: None,
+ entity_type: None,
+ version: enums::UserRoleVersion::V1,
+ };
+ db_user_roles.push(user_role.clone());
+ Ok(user_role)
}
async fn find_user_role_by_user_id(
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index b271abd1eff..33a1d5f53ca 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -83,9 +83,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Organization,
- is_invitable: false,
- is_deletable: false,
- is_updatable: false,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
is_internal: false,
},
);
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 19d682aeef1..a664fc84978 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -30,7 +30,7 @@ use crate::{
admin,
errors::{UserErrors, UserResult},
},
- db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
+ db::GlobalStorageInterface,
routes::SessionState,
services::{self, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
@@ -661,26 +661,17 @@ impl NewUser {
state: SessionState,
role_id: String,
user_status: UserStatus,
- version: Option<UserRoleVersion>,
) -> UserResult<UserRole> {
let org_id = self
.get_new_merchant()
.get_new_organization()
.get_organization_id();
- let merchant_id = self.get_new_merchant().get_merchant_id();
let org_user_role = self
.get_no_level_user_role(role_id, user_status)
- .add_entity(OrganizationLevel {
- org_id,
- merchant_id,
- });
-
- match version {
- Some(UserRoleVersion::V1) => org_user_role.insert_in_v1(&state).await,
- Some(UserRoleVersion::V2) => org_user_role.insert_in_v2(&state).await,
- None => org_user_role.insert_in_v1_and_v2(&state).await,
- }
+ .add_entity(OrganizationLevel { org_id });
+
+ org_user_role.insert_in_v2(&state).await
}
}
@@ -1119,8 +1110,6 @@ pub struct NoLevel;
#[derive(Clone)]
pub struct OrganizationLevel {
pub org_id: id_type::OrganizationId,
- // Keeping this to allow insertion of org_admins in V1
- pub merchant_id: id_type::MerchantId,
}
#[derive(Clone)]
@@ -1174,32 +1163,46 @@ pub struct EntityInfo {
entity_type: EntityType,
}
-impl<E> NewUserRole<E>
-where
- E: Clone,
-{
- fn convert_to_new_v1_role(
- self,
- org_id: id_type::OrganizationId,
- merchant_id: id_type::MerchantId,
- ) -> UserRoleNew {
- UserRoleNew {
- user_id: self.user_id,
- role_id: self.role_id,
- status: self.status,
- created_by: self.created_by,
- last_modified_by: self.last_modified_by,
- created_at: self.created_at,
- last_modified: self.last_modified,
- org_id: Some(org_id),
- merchant_id: Some(merchant_id),
+impl From<OrganizationLevel> for EntityInfo {
+ fn from(value: OrganizationLevel) -> Self {
+ Self {
+ entity_id: value.org_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Organization,
+ org_id: value.org_id,
+ merchant_id: None,
+ profile_id: None,
+ }
+ }
+}
+
+impl From<MerchantLevel> for EntityInfo {
+ fn from(value: MerchantLevel) -> Self {
+ Self {
+ entity_id: value.merchant_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Merchant,
+ org_id: value.org_id,
profile_id: None,
- entity_id: None,
- entity_type: None,
- version: UserRoleVersion::V1,
+ merchant_id: Some(value.merchant_id),
}
}
+}
+impl From<ProfileLevel> for EntityInfo {
+ fn from(value: ProfileLevel) -> Self {
+ Self {
+ entity_id: value.profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ org_id: value.org_id,
+ merchant_id: Some(value.merchant_id),
+ profile_id: Some(value.profile_id),
+ }
+ }
+}
+
+impl<E> NewUserRole<E>
+where
+ E: Clone + Into<EntityInfo>,
+{
fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew {
UserRoleNew {
user_id: self.user_id,
@@ -1218,116 +1221,15 @@ where
}
}
- async fn insert_v1_and_v2_in_db_and_get_v2(
- state: &SessionState,
- v1_role: UserRoleNew,
- v2_role: UserRoleNew,
- ) -> UserResult<UserRole> {
- let inserted_roles = state
- .store
- .insert_user_role(InsertUserRolePayload::V1AndV2(Box::new([v1_role, v2_role])))
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- inserted_roles
- .into_iter()
- .find(|role| role.version == UserRoleVersion::V2)
- .ok_or(report!(UserErrors::InternalServerError))
- }
-}
-
-impl NewUserRole<OrganizationLevel> {
- pub async fn insert_in_v1(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
-
- state
- .store
- .insert_user_role(InsertUserRolePayload::OnlyV1(new_v1_role))
- .await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
- }
-
pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
let entity = self.entity.clone();
- let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: None,
- profile_id: None,
- entity_id: entity.org_id.get_string_repr().to_owned(),
- entity_type: EntityType::Organization,
- });
- state
- .store
- .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
- .await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
- }
-
- pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
+ let new_v2_role = self.convert_to_new_v2_role(entity.into());
- let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: None,
- profile_id: None,
- entity_id: entity.org_id.get_string_repr().to_owned(),
- entity_type: EntityType::Organization,
- });
-
- Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
- }
-}
-
-impl NewUserRole<MerchantLevel> {
- pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone());
-
- let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: Some(entity.merchant_id.clone()),
- profile_id: None,
- entity_id: entity.merchant_id.get_string_repr().to_owned(),
- entity_type: EntityType::Merchant,
- });
-
- Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
- }
-}
-
-impl NewUserRole<ProfileLevel> {
- pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
-
- let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: Some(entity.merchant_id.clone()),
- profile_id: Some(entity.profile_id.clone()),
- entity_id: entity.profile_id.get_string_repr().to_owned(),
- entity_type: EntityType::Profile,
- });
state
.store
- .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role))
+ .insert_user_role(new_v2_role)
.await
- .change_context(UserErrors::InternalServerError)?
- .pop()
- .ok_or(report!(UserErrors::InternalServerError))
+ .change_context(UserErrors::InternalServerError)
}
}
| 2024-10-01T10:27:33Z |
## Description
<!-- Describe your changes in detail -->
Currently we are inserting user_roles in v1 version and v2 version. Since we have completely moved the APIs to support v2, we don't have to insert v1 anymore.
Allow inviting, updating and deleting org_admins.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6184
Closes #6186
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the following APIs will insert only v2 user_roles from now on.
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"name" : "name",
"email" : "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
},
{
"email": "email 2",
"name": "name",
"role_id": "merchant_admin"
}
]'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"company_name": "Juspay"
}'
```
You will now be able to invite org_admin
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "org_admin"
}
]'
``` | 4dae29221f2d24a0f4299e641cfe22ab705fae25 |
All the following APIs will insert only v2 user_roles from now on.
```curl
curl --location 'https://integ-api.hyperswitch.io/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "new email"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"name" : "name",
"email" : "new email",
"password": "password"
}'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "merchant_view_only"
},
{
"email": "email 2",
"name": "name",
"role_id": "merchant_admin"
}
]'
```
```
curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '{
"company_name": "Juspay"
}'
```
You will now be able to invite org_admin
```
curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data-raw '[
{
"email": "email",
"name": "name",
"role_id": "org_admin"
}
]'
```
| [
"crates/diesel_models/src/query/user_role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/user_role.rs",
"crates/router/src/services/authorization/roles/predefined_roles.rs",
"crates/router/src/types/domain/user.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5965 | Bug: [REFACTOR] Update Database Connection Functions for Read Operations
### Feature Description
Currently, in our codebase, we are using `pg_connection_write` for database operations even when performing read operations, which is inefficient. The `pg_connection_write` function should only be used when we need to perform write operations. For read operations, we should use `pg_connection_read` to optimize resource usage.
### Possible Implementation
Find occurrences of the usage of `pg_connection_write` for read operations and replace them with `pg_connection_read` in the following files:
- `crates/router/src/db/role.rs`
- `crates/router/src/db/user.rs`
- `crates/router/src/db/user_role.rs`
- `crates/router/src/db/dashboard_metadata.rs`
1. Open each of the specified files and search for functions that are performing read operations (for e.g., `find_by_*`, `get_*`) but are using `pg_connection_write`.
2. Replace the usage of `pg_connection_write` with `pg_connection_read` in these functions.
3. Ensure that the database calls still behave correctly and no write operations are mistakenly changed.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs
index f8aee34c49c..742c03dde4a 100644
--- a/crates/router/src/db/dashboard_metadata.rs
+++ b/crates/router/src/db/dashboard_metadata.rs
@@ -99,7 +99,7 @@ impl DashboardMetadataInterface for Store {
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::DashboardMetadata::find_user_scoped_dashboard_metadata(
&conn,
user_id.to_owned(),
@@ -118,7 +118,7 @@ impl DashboardMetadataInterface for Store {
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata(
&conn,
merchant_id.to_owned(),
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 20a4922d165..ce009d38a9e 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -80,7 +80,7 @@ impl RoleInterface for Store {
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id(&conn, role_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -93,7 +93,7 @@ impl RoleInterface for Store {
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id_in_merchant_scope(&conn, role_id, merchant_id, org_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -105,7 +105,7 @@ impl RoleInterface for Store {
role_id: &str,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id_in_org_scope(&conn, role_id, org_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -140,7 +140,7 @@ impl RoleInterface for Store {
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Role::list_roles(&conn, merchant_id, org_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -154,7 +154,7 @@ impl RoleInterface for Store {
entity_type: Option<enums::EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::Role::generic_roles_list_for_org(
&conn,
org_id.to_owned(),
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index c9244eb12b4..3cf68551b52 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -71,7 +71,7 @@ impl UserInterface for Store {
&self,
user_email: &pii::Email,
) -> CustomResult<storage::User, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_email(&conn, user_email)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -82,7 +82,7 @@ impl UserInterface for Store {
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
@@ -127,7 +127,7 @@ impl UserInterface for Store {
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::User::find_users_by_user_ids(&conn, user_ids)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index b589d375975..ceec7dd77d9 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -102,7 +102,7 @@ impl UserRoleInterface for Store {
profile_id: Option<&id_type::ProfileId>,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
+ let conn = connection::pg_connection_read(self).await?;
storage::UserRole::find_by_user_id_org_id_merchant_id_profile_id(
&conn,
user_id.to_owned(),
| 2024-09-30T19:50:45Z |
## Description
This PR refactors the database connection logic by changing the function from `pg_connection_write()` to `pg_connection_read()` for functions that only perform read operations from the database. This is an internal change aimed at optimizing resource usage. All user-facing APIs should continue to function as expected without any disruptions.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## Motivation and Context
This change is required to improve efficiency by ensuring that we use the appropriate connection type for read operations. It resolves the inefficiency of using write connections for read-only database queries.
- Fixes https://github.com/juspay/hyperswitch/issues/5965
## How did you test it?
- Verified that all user-related APIs are working without any issues.
- All existing test cases for database read and write operations passed successfully.
- Confirmed that this internal change does not affect the functionality of user-facing APIs. | edd099886da9c46800a646fe809796a08eb78c99 | - Verified that all user-related APIs are working without any issues.
- All existing test cases for database read and write operations passed successfully.
- Confirmed that this internal change does not affect the functionality of user-facing APIs.
| [
"crates/router/src/db/dashboard_metadata.rs",
"crates/router/src/db/role.rs",
"crates/router/src/db/user.rs",
"crates/router/src/db/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6165 | Bug: [FIX] use batch encryption/decryption for payment intent table
| diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index bd4707243ce..562e5d205c0 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1,14 +1,14 @@
use common_enums as storage_enums;
use common_utils::{
consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2},
- crypto::Encryptable,
+ crypto::{self, Encryptable},
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type,
pii::{self, Email},
type_name,
types::{
- keymanager::{self, KeyManagerState},
+ keymanager::{self, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
@@ -17,6 +17,7 @@ use diesel_models::{
};
use error_stack::ResultExt;
use masking::{Deserialize, PeekInterface, Secret};
+use rustc_hash::FxHashMap;
use serde::Serialize;
use time::PrimitiveDateTime;
@@ -26,7 +27,7 @@ use super::PaymentIntent;
use crate::{
behaviour, errors,
merchant_key_store::MerchantKeyStore,
- type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
+ type_encryption::{crypto_operation, CryptoOperation},
RemoteStorageObject,
};
#[async_trait::async_trait]
@@ -1568,17 +1569,25 @@ impl behaviour::Conversion for PaymentIntent {
Self: Sized,
{
async {
- let inner_decrypt = |inner| async {
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::DecryptOptional(inner),
- key_manager_identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- };
+ let decrypted_data = crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable(
+ EncryptedPaymentIntentAddress {
+ billing: storage_model.billing_address,
+ shipping: storage_model.shipping_address,
+ customer_details: storage_model.customer_details,
+ },
+ )),
+ key_manager_identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
+
+ let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data)
+ .change_context(common_utils::errors::CryptoError::DecodingFailed)
+ .attach_printable("Invalid batch operation data")?;
let amount_details = super::AmountDetails {
order_amount: storage_model.amount,
@@ -1628,18 +1637,9 @@ impl behaviour::Conversion for PaymentIntent {
storage_model.request_external_three_ds_authentication,
),
frm_metadata: storage_model.frm_metadata,
- customer_details: storage_model
- .customer_details
- .async_lift(inner_decrypt)
- .await?,
- billing_address: storage_model
- .billing_address
- .async_lift(inner_decrypt)
- .await?,
- shipping_address: storage_model
- .shipping_address
- .async_lift(inner_decrypt)
- .await?,
+ customer_details: data.customer_details,
+ billing_address: data.billing,
+ shipping_address: data.shipping,
capture_method: storage_model.capture_method,
id: storage_model.id,
merchant_reference_id: storage_model.merchant_reference_id,
@@ -1796,17 +1796,26 @@ impl behaviour::Conversion for PaymentIntent {
Self: Sized,
{
async {
- let inner_decrypt = |inner| async {
- crypto_operation(
- state,
- type_name!(Self::DstType),
- CryptoOperation::DecryptOptional(inner),
- key_manager_identifier.clone(),
- key.peek(),
- )
- .await
- .and_then(|val| val.try_into_optionaloperation())
- };
+ let decrypted_data = crypto_operation(
+ state,
+ type_name!(Self::DstType),
+ CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable(
+ EncryptedPaymentIntentAddress {
+ billing: storage_model.billing_details,
+ shipping: storage_model.shipping_details,
+ customer_details: storage_model.customer_details,
+ },
+ )),
+ key_manager_identifier,
+ key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())?;
+
+ let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data)
+ .change_context(common_utils::errors::CryptoError::DecodingFailed)
+ .attach_printable("Invalid batch operation data")?;
+
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
@@ -1854,19 +1863,10 @@ impl behaviour::Conversion for PaymentIntent {
frm_metadata: storage_model.frm_metadata,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
- customer_details: storage_model
- .customer_details
- .async_lift(inner_decrypt)
- .await?,
- billing_details: storage_model
- .billing_details
- .async_lift(inner_decrypt)
- .await?,
+ customer_details: data.customer_details,
+ billing_details: data.billing,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
- shipping_details: storage_model
- .shipping_details
- .async_lift(inner_decrypt)
- .await?,
+ shipping_details: data.shipping,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
organization_id: storage_model.organization_id,
skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
@@ -1935,3 +1935,73 @@ impl behaviour::Conversion for PaymentIntent {
})
}
}
+
+pub struct EncryptedPaymentIntentAddress {
+ pub shipping: Option<Encryption>,
+ pub billing: Option<Encryption>,
+ pub customer_details: Option<Encryption>,
+}
+
+pub struct PaymentAddressFromRequest {
+ pub shipping: Option<Secret<serde_json::Value>>,
+ pub billing: Option<Secret<serde_json::Value>>,
+ pub customer_details: Option<Secret<serde_json::Value>>,
+}
+
+pub struct DecryptedPaymentIntentAddress {
+ pub shipping: crypto::OptionalEncryptableValue,
+ pub billing: crypto::OptionalEncryptableValue,
+ pub customer_details: crypto::OptionalEncryptableValue,
+}
+
+impl ToEncryptable<DecryptedPaymentIntentAddress, Secret<serde_json::Value>, Encryption>
+ for EncryptedPaymentIntentAddress
+{
+ fn from_encryptable(
+ mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>,
+ ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> {
+ Ok(DecryptedPaymentIntentAddress {
+ shipping: hashmap.remove("shipping"),
+ billing: hashmap.remove("billing"),
+ customer_details: hashmap.remove("customer_details"),
+ })
+ }
+
+ fn to_encryptable(self) -> FxHashMap<String, Encryption> {
+ let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default());
+
+ self.shipping.map(|s| map.insert("shipping".to_string(), s));
+ self.billing.map(|s| map.insert("billing".to_string(), s));
+ self.customer_details
+ .map(|s| map.insert("customer_details".to_string(), s));
+ map
+ }
+}
+
+impl
+ ToEncryptable<
+ DecryptedPaymentIntentAddress,
+ Secret<serde_json::Value>,
+ Secret<serde_json::Value>,
+ > for PaymentAddressFromRequest
+{
+ fn from_encryptable(
+ mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>,
+ ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> {
+ Ok(DecryptedPaymentIntentAddress {
+ shipping: hashmap.remove("shipping"),
+ billing: hashmap.remove("billing"),
+ customer_details: hashmap.remove("customer_details"),
+ })
+ }
+
+ fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> {
+ let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default());
+
+ self.shipping.map(|s| map.insert("shipping".to_string(), s));
+ self.billing.map(|s| map.insert("billing".to_string(), s));
+ self.customer_details
+ .map(|s| map.insert("customer_details".to_string(), s));
+ map
+ }
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 31cfae49875..5becef839d5 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -17,7 +17,7 @@ email = ["external_services/email", "scheduler/email", "olap"]
# keymanager_create, keymanager_mtls, encryption_service should not be removed or added to default feature. Once this features were enabled it can't be disabled as these are breaking changes.
keymanager_create = []
keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"]
-encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"]
+encryption_service = ["keymanager_create","hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"]
km_forward_x_request_id = ["common_utils/km_forward_x_request_id"]
frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"]
stripe = []
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index d27b6b82fd4..099ce4aced1 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -194,7 +194,7 @@ pub async fn create_merchant_account(
let master_key = db.get_master_key();
- let key_manager_state = &(&state).into();
+ let key_manager_state: &KeyManagerState = &(&state).into();
let merchant_id = req.get_merchant_reference_id();
let identifier = km_types::Identifier::Merchant(merchant_id.clone());
#[cfg(feature = "keymanager_create")]
@@ -203,16 +203,18 @@ pub async fn create_merchant_account(
use crate::consts::BASE64_ENGINE;
- keymanager::transfer_key_to_key_manager(
- key_manager_state,
- EncryptionTransferRequest {
- identifier: identifier.clone(),
- key: BASE64_ENGINE.encode(key),
- },
- )
- .await
- .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount)
- .attach_printable("Failed to insert key to KeyManager")?;
+ if key_manager_state.enabled {
+ keymanager::transfer_key_to_key_manager(
+ key_manager_state,
+ EncryptionTransferRequest {
+ identifier: identifier.clone(),
+ key: BASE64_ENGINE.encode(key),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount)
+ .attach_printable("Failed to insert key to KeyManager")?;
+ }
}
let key_store = domain::MerchantKeyStore {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 51f2de51f26..0921e38317a 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -7,13 +7,20 @@ use api_models::{
use async_trait::async_trait;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
- types::{keymanager::KeyManagerState, MinorUnit},
+ type_name,
+ types::{
+ keymanager::{Identifier, KeyManagerState, ToEncryptable},
+ MinorUnit,
+ },
};
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
- payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData},
+ payments::{
+ payment_attempt::PaymentAttempt,
+ payment_intent::{CustomerData, PaymentAddressFromRequest},
+ },
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
@@ -1280,28 +1287,6 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)?
.map(Secret::new);
- // Derivation of directly supplied Billing Address data in our Payment Create Request
- // Encrypting our Billing Address Details to be stored in Payment Intent
- let billing_details = request
- .billing
- .clone()
- .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details))
- .await
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt billing details")?;
-
- // Derivation of directly supplied Shipping Address data in our Payment Create Request
- // Encrypting our Shipping Address Details to be stored in Payment Intent
- let shipping_details = request
- .shipping
- .clone()
- .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details))
- .await
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt shipping details")?;
-
// Derivation of directly supplied Customer data in our Payment Create Request
let raw_customer_details = if request.customer_id.is_none()
&& (request.name.is_some()
@@ -1325,13 +1310,53 @@ impl PaymentCreate {
},
);
- // Encrypting our Customer Details to be stored in Payment Intent
- let customer_details = raw_customer_details
- .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details))
- .await
+ let key = key_store.key.get_inner().peek();
+ let identifier = Identifier::Merchant(key_store.merchant_id.clone());
+ let key_manager_state: KeyManagerState = state.into();
+
+ let shipping_details_encoded = request
+ .shipping
+ .clone()
+ .map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt customer details")?;
+ .attach_printable("Unable to encode billing details to serde_json::Value")?;
+
+ let billing_details_encoded = request
+ .billing
+ .clone()
+ .map(|billing| Encode::encode_to_value(&billing).map(Secret::new))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encode billing details to serde_json::Value")?;
+
+ let customer_details_encoded = raw_customer_details
+ .map(|customer| Encode::encode_to_value(&customer).map(Secret::new))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encode shipping details to serde_json::Value")?;
+
+ let encrypted_data = domain::types::crypto_operation(
+ &key_manager_state,
+ type_name!(storage::PaymentIntent),
+ domain::types::CryptoOperation::BatchEncrypt(
+ PaymentAddressFromRequest::to_encryptable(PaymentAddressFromRequest {
+ shipping: shipping_details_encoded,
+ billing: billing_details_encoded,
+ customer_details: customer_details_encoded,
+ }),
+ ),
+ identifier.clone(),
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt data")?;
+
+ let encrypted_data = PaymentAddressFromRequest::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt the payment intent data")?;
let skip_external_tax_calculation = request.skip_external_tax_calculation;
@@ -1382,10 +1407,10 @@ impl PaymentCreate {
.request_external_three_ds_authentication,
charges,
frm_metadata: request.frm_metadata.clone(),
- billing_details,
- customer_details,
+ billing_details: encrypted_data.billing,
+ customer_details: encrypted_data.customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
- shipping_details,
+ shipping_details: encrypted_data.shipping,
is_payment_processor_token_flow,
organization_id: merchant_account.organization_id.clone(),
shipping_cost: request.shipping_cost,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 7444fea0c3b..197c1e4c52a 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -496,7 +496,7 @@ pub async fn send_request(
))
};
- // We cannot clone the request type, because it has Form trait which is not clonable. So we are cloning the request builder here.
+ // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here.
let cloned_send_request = request.try_clone().map(|cloned_request| async {
cloned_request
.send()
@@ -570,7 +570,7 @@ pub async fn send_request(
.await
}
None => {
- logger::info!("Retrying request due to connection closed before message could complete failed as request is not clonable");
+ logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable");
Err(error)
}
}
| 2024-09-30T16:08:45Z |
## Description
<!-- Describe your changes in detail -->
Batch Encrypt/Decrypt fields in Payment Intent table
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Currently all the encryption/Decryption operation is happening serially. Which adds additional latency, So this PR fixes it by using the Batch encryption/decryption API of Keymanager
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### How to test it in deployed environments
Basic sanity testing of `PaymentsCreate` and `PaymentsList`.
### How did I test it locally
1. Call /payments from postman
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \
--data-raw '{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "HScustomer1234",
"email": "p143@example.com",
"amount_to_capture": 600,
"description": "Its my first payment request",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"name": "Preetam",
"phone": "999999999",
"setup_future_usage": "off_session",
"phone_country_code": "+65",
"authentication_type": "three_ds",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"connector_metadata": {
"noon": {
"order_category": "applepay"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "preetam",
"last_name": "revankar"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
],
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
3. Check if the encryption/decryption call happening only once in the logs.
<img width="1354" alt="Screenshot 2024-10-01 at 1 19 45 PM" src="https://github.com/user-attachments/assets/09ba719a-4ef7-4c17-9dd4-cc9cbb6dbe57">
<img width="1354" alt="Screenshot 2024-10-01 at 1 18 59 PM" src="https://github.com/user-attachments/assets/b8e185fd-22ca-4b11-aab0-74da4a3cd604"> | 6b0f7e4870886997ca300935e727283c739be486 |
### How to test it in deployed environments
Basic sanity testing of `PaymentsCreate` and `PaymentsList`.
### How did I test it locally
1. Call /payments from postman
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \
--data-raw '{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "HScustomer1234",
"email": "p143@example.com",
"amount_to_capture": 600,
"description": "Its my first payment request",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"name": "Preetam",
"phone": "999999999",
"setup_future_usage": "off_session",
"phone_country_code": "+65",
"authentication_type": "three_ds",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "737"
}
},
"connector_metadata": {
"noon": {
"order_category": "applepay"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "preetam",
"last_name": "revankar"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
],
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
3. Check if the encryption/decryption call happening only once in the logs.
<img width="1354" alt="Screenshot 2024-10-01 at 1 19 45 PM" src="https://github.com/user-attachments/assets/09ba719a-4ef7-4c17-9dd4-cc9cbb6dbe57">
<img width="1354" alt="Screenshot 2024-10-01 at 1 18 59 PM" src="https://github.com/user-attachments/assets/b8e185fd-22ca-4b11-aab0-74da4a3cd604">
| [
"crates/hyperswitch_domain_models/src/payments/payment_intent.rs",
"crates/router/Cargo.toml",
"crates/router/src/core/admin.rs",
"crates/router/src/core/payments/operations/payment_create.rs",
"crates/router/src/services/api.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6163 | Bug: fix(payments): remove time range filter from payment attempt hotfix
Corresponding issue: https://github.com/juspay/hyperswitch/issues/6160 | diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 48941330ec6..fa80b0990d1 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -351,7 +351,6 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
@@ -361,14 +360,6 @@ impl PaymentAttempt {
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
- if let Some(time_range) = time_range {
- filter = filter.filter(dsl::created_at.ge(time_range.start_time));
-
- if let Some(end_time) = time_range.end_time {
- filter = filter.filter(dsl::created_at.le(end_time));
- }
- }
-
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 003509b2039..24a79e2905e 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -156,7 +156,6 @@ pub trait PaymentAttemptInterface {
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 4bfca852fb0..d951236c94c 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3179,7 +3179,6 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
- constraints.time_range,
pi_fetch_constraints.get_profile_id_list(),
merchant.storage_scheme,
)
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index d14de8c2330..e0ff815fa76 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1606,7 +1606,6 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
@@ -1619,7 +1618,6 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
- time_range,
profile_id_list,
storage_scheme,
)
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 7abde140991..1a4595bdbbe 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -52,7 +52,6 @@ impl PaymentAttemptInterface for MockDb {
_payment_method_type: Option<Vec<PaymentMethodType>>,
_authentication_type: Option<Vec<AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- _time_range: Option<common_utils::types::TimeRange>,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 9974393e100..d1df6861657 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -403,7 +403,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -427,7 +426,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
- time_range,
profile_id_list,
merchant_connector_id,
)
@@ -1291,7 +1289,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -1304,7 +1301,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
- time_range,
profile_id_list,
storage_scheme,
)
| 2024-09-30T14:44:08Z |
## Description
Corresponding main branch PR: #6159
Currently created_at is not indexed in payment attempt table, when applying filtering with active attempt ids. We are adding extra overhead of checking time_range, though we need not to as we will be already getting filtered attempt ids from intent table.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#6163](https://github.com/juspay/hyperswitch/issues/6163)
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
--> | 387f02ee273e1bbf50e7b3882f5e9468d59f2c5b | [
"crates/diesel_models/src/query/payment_attempt.rs",
"crates/hyperswitch_domain_models/src/payments/payment_attempt.rs",
"crates/router/src/core/payments.rs",
"crates/router/src/db/kafka_store.rs",
"crates/storage_impl/src/mock_db/payment_attempt.rs",
"crates/storage_impl/src/payments/payment_attempt.rs"
... | ||
juspay/hyperswitch | juspay__hyperswitch-6160 | Bug: fix(payments): remove time range filter from payment attempt
We don't need time range filters since created at is not indexed in payments attempts, we are already getting filtered payments intents and using its active attempt ids. It is further slowing down 'IN' query performance. | diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index e07d716fb6c..ad056aef6d0 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -369,7 +369,6 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
@@ -379,14 +378,6 @@ impl PaymentAttempt {
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
- if let Some(time_range) = time_range {
- filter = filter.filter(dsl::created_at.ge(time_range.start_time));
-
- if let Some(end_time) = time_range.end_time {
- filter = filter.filter(dsl::created_at.le(end_time));
- }
- }
-
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 5f0894566ad..c71e08c79e8 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -157,7 +157,6 @@ pub trait PaymentAttemptInterface {
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index d00d4b7b259..6e785b55a3f 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3243,7 +3243,6 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
- constraints.time_range,
pi_fetch_constraints.get_profile_id_list(),
merchant.storage_scheme,
)
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 73d05528634..de10b70f507 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1604,7 +1604,6 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
@@ -1617,7 +1616,6 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
- time_range,
profile_id_list,
storage_scheme,
)
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 44c089932d9..c37f9f6d3da 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -52,7 +52,6 @@ impl PaymentAttemptInterface for MockDb {
_payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
_authentication_type: Option<Vec<common_enums::AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- _time_range: Option<common_utils::types::TimeRange>,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 6d669437efd..63f5a0ff9f8 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -403,7 +403,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -427,7 +426,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
- time_range,
profile_id_list,
merchant_connector_id,
)
@@ -1289,7 +1287,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
- time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -1302,7 +1299,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
- time_range,
profile_id_list,
storage_scheme,
)
| 2024-09-30T13:32:34Z |
## Description
Currently `created_at` is not indexed in payment attempt table, when applying filtering with active attempt ids. We are adding extra overhead of checking time_range, though we need not to as we will be already getting filtered attempt ids from intent table.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#6160](https://github.com/juspay/hyperswitch/issues/6160)
## How did you test it?
We can hit test api
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"limit": 50,
}'
``` | e4a35d366b7db151378d6c1f61e4d01d1c7ed37f | We can hit test api
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"limit": 50,
}'
```
| [
"crates/diesel_models/src/query/payment_attempt.rs",
"crates/hyperswitch_domain_models/src/payments/payment_attempt.rs",
"crates/router/src/core/payments.rs",
"crates/router/src/db/kafka_store.rs",
"crates/storage_impl/src/mock_db/payment_attempt.rs",
"crates/storage_impl/src/payments/payment_attempt.rs"
... | |
juspay/hyperswitch | juspay__hyperswitch-6157 | Bug: [FEATURE] [DLOCAL, SQUARE] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `dlocal` and `square` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `dlocal` and `square` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index f057b7d4a33..9406353a1ee 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -4,6 +4,7 @@ pub mod cashtocode;
pub mod coinbase;
pub mod cryptopay;
pub mod deutschebank;
+pub mod dlocal;
pub mod fiserv;
pub mod fiservemea;
pub mod fiuu;
@@ -13,6 +14,7 @@ pub mod mollie;
pub mod nexixpay;
pub mod novalnet;
pub mod powertranz;
+pub mod square;
pub mod stax;
pub mod taxjar;
pub mod thunes;
@@ -22,8 +24,8 @@ pub mod worldline;
pub use self::{
bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
- cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea,
- fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay,
- novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
- tsys::Tsys, volt::Volt, worldline::Worldline,
+ cryptopay::Cryptopay, deutschebank::Deutschebank, dlocal::Dlocal, fiserv::Fiserv,
+ fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie,
+ nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, square::Square, stax::Stax,
+ taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs
similarity index 68%
rename from crates/router/src/connector/dlocal.rs
rename to crates/hyperswitch_connectors/src/connectors/dlocal.rs
index dc99619e9da..78d3ad4f63e 100644
--- a/crates/router/src/connector/dlocal.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs
@@ -2,36 +2,51 @@ pub mod transformers;
use std::fmt::Debug;
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
use common_utils::{
crypto::{self, SignMessage},
date_time,
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
};
-use diesel_models::enums;
use error_stack::{report, ResultExt};
use hex::encode;
-use masking::PeekInterface;
-use transformers as dlocal;
-
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers, logger,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{Mask, Maskable, PeekInterface};
+use transformers as dlocal;
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self},
+};
#[derive(Debug, Clone)]
pub struct Dlocal;
@@ -54,9 +69,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let dlocal_req = self.get_request_body(req, connectors)?;
let date = date_time::date_as_yyyymmddthhmmssmmmz()
@@ -110,7 +125,7 @@ impl ConnectorCommon for Dlocal {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dlocal.base_url.as_ref()
}
@@ -148,49 +163,30 @@ impl ConnectorValidation for Dlocal {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Dlocal
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Dlocal
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Dlocal
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Dlocal
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Dlocal
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string())
.into(),
@@ -198,14 +194,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Dlocal
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -215,16 +209,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}secure_payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = dlocal::DlocalRouterData::try_from((
&self.get_currency_unit(),
@@ -238,12 +232,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -260,11 +254,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- logger::debug!(dlocal_payments_authorize_response=?res);
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_payments_authorize_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsAuthorizeResponse")
@@ -273,7 +267,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -290,14 +284,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Dlocal
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -307,8 +299,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let sync_data = dlocal::DlocalPaymentsSyncRequest::try_from(req)?;
Ok(format!(
@@ -320,12 +312,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -343,18 +335,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- logger::debug!(dlocal_payment_sync_response=?res);
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_payment_sync_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -363,14 +355,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Dlocal
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -380,16 +370,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dlocal::DlocalPaymentsCaptureRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -397,12 +387,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -417,18 +407,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- logger::debug!(dlocal_payments_capture_response=?res);
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_payments_capture_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -445,14 +435,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Dlocal
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -462,8 +450,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let cancel_data = dlocal::DlocalPaymentsCancelRequest::try_from(req)?;
Ok(format!(
@@ -475,12 +463,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -490,11 +478,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
- logger::debug!(dlocal_payments_cancel_response=?res);
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_payments_cancel_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal PaymentsCancelResponse")
@@ -502,7 +490,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -519,12 +507,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Dlocal {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -534,16 +522,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = dlocal::DlocalRouterData::try_from((
&self.get_currency_unit(),
@@ -557,11 +545,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -576,18 +564,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- logger::debug!(dlocal_refund_response=?res);
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_refund_response=?res);
let response: dlocal::RefundResponse =
res.response
.parse_struct("Dlocal RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -604,12 +592,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Dlocal {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dlocal {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -619,8 +607,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let sync_data = dlocal::DlocalRefundsSyncRequest::try_from(req)?;
Ok(format!(
@@ -632,12 +620,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -647,18 +635,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- logger::debug!(dlocal_refund_sync_response=?res);
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ router_env::logger::debug!(dlocal_refund_sync_response=?res);
let response: dlocal::RefundResponse = res
.response
.parse_struct("Dlocal RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -676,24 +664,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Dlocal {
+impl webhooks::IncomingWebhook for Dlocal {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
similarity index 77%
rename from crates/router/src/connector/dlocal/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
index a613cdb2054..385601294b3 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
@@ -1,15 +1,23 @@
use api_models::payments::AddressDetails;
-use common_utils::pii::Email;
+use common_enums::enums;
+use common_utils::{pii::Email, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::{refunds::Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::{api::CurrencyUnit, errors};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _},
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
@@ -57,16 +65,11 @@ pub struct DlocalRouterData<T> {
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> {
+impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (_currency_unit, _currency, amount, router_data): (
- &api::CurrencyUnit,
- enums::Currency,
- i64,
- T,
- ),
+ (_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -100,7 +103,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
let country = address.get_country()?;
let name = get_payer_name(address);
match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
+ PaymentMethodData::Card(ref ccard) => {
let should_capture = matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic)
@@ -143,38 +146,34 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
}),
order_id: item.router_data.connector_request_reference_id.clone(),
three_dsecure: match item.router_data.auth_type {
- diesel_models::enums::AuthenticationType::ThreeDs => {
+ enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
}
- diesel_models::enums::AuthenticationType::NoThreeDs => None,
+ enums::AuthenticationType::NoThreeDs => None,
},
callback_url: Some(item.router_data.request.get_router_return_url()?),
description: item.router_data.description.clone(),
};
Ok(payment_request)
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- crate::connector::utils::get_unimplemented_payment_method_error_message(
- "Dlocal",
- ),
- ))?
- }
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
+ ))?,
}
}
}
@@ -252,10 +251,10 @@ pub struct DlocalAuthType {
pub(super) secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for DlocalAuthType {
+impl TryFrom<&ConnectorAuthType> for DlocalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -309,24 +308,21 @@ pub struct DlocalPaymentsResponse {
order_id: Option<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.three_dsecure
.and_then(|three_secure_data| three_secure_data.redirect_url)
- .map(|redirect_url| {
- services::RedirectForm::from((redirect_url, services::Method::Get))
- });
+ .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
- let response = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ let response = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
@@ -350,24 +346,17 @@ pub struct DlocalPaymentsSyncResponse {
order_id: Option<String>,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, DlocalPaymentsSyncResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- DlocalPaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -388,24 +377,17 @@ pub struct DlocalPaymentsCaptureResponse {
order_id: Option<String>,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- DlocalPaymentsCaptureResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -424,26 +406,17 @@ pub struct DlocalPaymentsCancelResponse {
order_id: String,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, DlocalPaymentsCancelResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- DlocalPaymentsCancelResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.order_id.clone(),
- ),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -509,16 +482,16 @@ pub struct RefundResponse {
pub status: RefundStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
@@ -545,16 +518,14 @@ impl TryFrom<&types::RefundSyncRouterData> for DlocalRefundsSyncRequest {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
diff --git a/crates/router/src/connector/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs
similarity index 65%
rename from crates/router/src/connector/square.rs
rename to crates/hyperswitch_connectors/src/connectors/square.rs
index 9b9c68a5f2b..bf2cd4e1ace 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square.rs
@@ -2,31 +2,54 @@ pub mod transformers;
use std::fmt::Debug;
-use api_models::enums;
+use api_models::{
+ enums,
+ webhooks::{IncomingWebhookEvent, ObjectReferenceId},
+};
use base64::Engine;
-use common_utils::{ext_traits::ByteSliceExt, request::RequestContent};
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use masking::PeekInterface;
-use transformers as square;
-
-use super::utils::{self as super_utils, RefundsRequestData};
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ AuthorizeSessionToken,
},
+ router_request_types::{
+ AccessTokenRequestData, AuthorizeSessionTokenData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData,
+ PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
- utils::BytesExt,
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, PaymentsAuthorizeType, Response},
+ webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
+};
+use masking::{Mask, Maskable, PeekInterface};
+use transformers::{
+ self as square, SquareAuthType, SquarePaymentsRequest, SquareRefundRequest, SquareTokenRequest,
+};
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, get_header_key_value, RefundsRequestData},
};
#[derive(Debug, Clone)]
@@ -52,12 +75,12 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
@@ -76,15 +99,15 @@ impl ConnectorCommon for Square {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.square.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let auth = square::SquareAuthType::try_from(auth_type)
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ let auth = SquareAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
@@ -142,39 +165,24 @@ impl ConnectorValidation for Square {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- super::utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Square
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Square {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Square
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Square {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Square
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Square {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Square".to_string())
.into(),
@@ -183,18 +191,14 @@ impl
}
#[async_trait::async_trait]
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Square
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Square
{
fn get_headers(
&self,
- _req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &TokenizationRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
types::TokenizationType::get_content_type(self)
@@ -209,8 +213,8 @@ impl
fn get_url(
&self,
- _req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
+ _req: &TokenizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v2/card-nonce",
@@ -224,22 +228,22 @@ impl
fn get_request_body(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = square::SquareTokenRequest::try_from(req)?;
+ let connector_req = SquareTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
@@ -252,12 +256,12 @@ impl
fn handle_response(
&self,
- data: &types::TokenizationRouterData,
+ data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
let response: square::SquareTokenResponse = res
.response
@@ -267,7 +271,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -282,21 +286,17 @@ impl
}
}
-impl
- ConnectorIntegration<
- api::AuthorizeSessionToken,
- types::AuthorizeSessionTokenData,
- types::PaymentsResponseData,
- > for Square
+impl ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>
+ for Square
{
fn get_headers(
&self,
- _req: &types::PaymentsAuthorizeSessionTokenRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &PaymentsAuthorizeSessionTokenRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)])
@@ -308,10 +308,10 @@ impl
fn get_url(
&self,
- req: &types::PaymentsAuthorizeSessionTokenRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeSessionTokenRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let auth = square::SquareAuthType::try_from(&req.connector_auth_type)
+ let auth = SquareAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
@@ -327,12 +327,12 @@ impl
fn build_request(
&self,
- req: &types::PaymentsAuthorizeSessionTokenRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeSessionTokenRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsPreAuthorizeType::get_url(
self, req, connectors,
)?)
@@ -346,10 +346,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeSessionTokenRouterData,
+ data: &PaymentsAuthorizeSessionTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
let response: square::SquareSessionResponse = res
.response
.parse_struct("SquareSessionResponse")
@@ -358,7 +358,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -374,14 +374,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Square
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Square {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -391,38 +389,34 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = square::SquarePaymentsRequest::try_from(req)?;
+ let connector_req = SquarePaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -431,10 +425,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsAuthorizeResponse")
@@ -443,7 +437,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -459,14 +453,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Square
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Square {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -476,8 +468,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
@@ -493,12 +485,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
@@ -508,10 +500,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsSyncResponse")
@@ -520,7 +512,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -536,14 +528,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Square
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Square {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -553,8 +543,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v2/payments/{}/complete",
@@ -565,9 +555,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
if req.request.amount_to_capture != req.request.payment_amount {
Err(errors::ConnectorError::NotSupported {
message: "Partial Capture".to_string(),
@@ -575,8 +565,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
})?
}
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
@@ -588,10 +578,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsCaptureResponse")
@@ -600,7 +590,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -616,14 +606,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Square
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Square {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -633,8 +621,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v2/payments/{}/cancel",
@@ -645,12 +633,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
@@ -660,10 +648,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: square::SquarePaymentsResponse = res
.response
.parse_struct("SquarePaymentsVoidResponse")
@@ -672,7 +660,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -688,12 +676,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Square {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Square {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -703,28 +691,28 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/refunds", self.base_url(connectors),))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = square::SquareRefundRequest::try_from(req)?;
+ let connector_req = SquareRefundRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -739,10 +727,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: square::RefundResponse = res
.response
.parse_struct("SquareRefundResponse")
@@ -751,7 +739,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -767,12 +755,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Square {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Square {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -782,8 +770,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v2/refunds/{}",
@@ -794,12 +782,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
+ RequestBuilder::new()
+ .method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
@@ -809,10 +797,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: square::RefundResponse = res
.response
.parse_struct("SquareRefundSyncResponse")
@@ -821,7 +809,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -838,10 +826,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Square {
+impl IncomingWebhook for Square {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError>
{
Ok(Box::new(common_utils::crypto::HmacSha256))
@@ -849,12 +837,12 @@ impl api::IncomingWebhook for Square {
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let encoded_signature =
- super_utils::get_header_key_value("x-square-hmacsha256-signature", request.headers)?;
- let signature = consts::BASE64_ENGINE
+ get_header_key_value("x-square-hmacsha256-signature", request.headers)?;
+ let signature = common_utils::consts::BASE64_ENGINE
.decode(encoded_signature)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
Ok(signature)
@@ -862,7 +850,7 @@ impl api::IncomingWebhook for Square {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -885,43 +873,37 @@ impl api::IncomingWebhook for Square {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let webhook_body: square::SquareWebhookBody = request
.body
.parse_struct("SquareWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match webhook_body.data.object {
- square::SquareWebhookObject::Payment(_) => {
- Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
- api_models::payments::PaymentIdType::ConnectorTransactionId(
- webhook_body.data.id,
- ),
- ))
- }
- square::SquareWebhookObject::Refund(_) => {
- Ok(api_models::webhooks::ObjectReferenceId::RefundId(
- api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id),
- ))
- }
+ square::SquareWebhookObject::Payment(_) => Ok(ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.data.id),
+ )),
+ square::SquareWebhookObject::Refund(_) => Ok(ObjectReferenceId::RefundId(
+ api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id),
+ )),
}
}
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: square::SquareWebhookBody = request
.body
.parse_struct("SquareWebhookEventType")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
- Ok(api::IncomingWebhookEvent::from(details.data.object))
+ Ok(IncomingWebhookEvent::from(details.data.object))
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: square::SquareWebhookBody =
request
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
similarity index 59%
rename from crates/router/src/connector/square/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index db7058f3384..4e2b30a574b 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -1,38 +1,44 @@
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{BankDebitData, Card, PayLaterData, PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
+ router_flow_types::{refunds::Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types,
+};
+use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
+ utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
-impl TryFrom<(&types::TokenizationRouterData, domain::BankDebitData)> for SquareTokenRequest {
+impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: (&types::TokenizationRouterData, domain::BankDebitData),
+ value: (&types::TokenizationRouterData, BankDebitData),
) -> Result<Self, Self::Error> {
let (_item, bank_debit_data) = value;
match bank_debit_data {
- domain::BankDebitData::AchBankDebit { .. }
- | domain::BankDebitData::SepaBankDebit { .. }
- | domain::BankDebitData::BecsBankDebit { .. }
- | domain::BankDebitData::BacsBankDebit { .. } => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?
- }
+ BankDebitData::AchBankDebit { .. }
+ | BankDebitData::SepaBankDebit { .. }
+ | BankDebitData::BecsBankDebit { .. }
+ | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?,
}
}
}
-impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequest {
+impl TryFrom<(&types::TokenizationRouterData, Card)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- value: (&types::TokenizationRouterData, domain::Card),
- ) -> Result<Self, Self::Error> {
+ fn try_from(value: (&types::TokenizationRouterData, Card)) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let auth = SquareAuthType::try_from(&item.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
@@ -69,63 +75,59 @@ impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequ
}
}
-impl TryFrom<(&types::TokenizationRouterData, domain::PayLaterData)> for SquareTokenRequest {
+impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: (&types::TokenizationRouterData, domain::PayLaterData),
+ value: (&types::TokenizationRouterData, PayLaterData),
) -> Result<Self, Self::Error> {
let (_item, pay_later_data) = value;
match pay_later_data {
- domain::PayLaterData::AfterpayClearpayRedirect { .. }
- | domain::PayLaterData::KlarnaRedirect { .. }
- | domain::PayLaterData::KlarnaSdk { .. }
- | domain::PayLaterData::AffirmRedirect { .. }
- | domain::PayLaterData::PayBrightRedirect { .. }
- | domain::PayLaterData::WalleyRedirect { .. }
- | domain::PayLaterData::AlmaRedirect { .. }
- | domain::PayLaterData::AtomeRedirect { .. } => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?
- }
+ PayLaterData::AfterpayClearpayRedirect { .. }
+ | PayLaterData::KlarnaRedirect { .. }
+ | PayLaterData::KlarnaSdk { .. }
+ | PayLaterData::AffirmRedirect { .. }
+ | PayLaterData::PayBrightRedirect { .. }
+ | PayLaterData::WalleyRedirect { .. }
+ | PayLaterData::AlmaRedirect { .. }
+ | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?,
}
}
}
-impl TryFrom<(&types::TokenizationRouterData, domain::WalletData)> for SquareTokenRequest {
+impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- value: (&types::TokenizationRouterData, domain::WalletData),
- ) -> Result<Self, Self::Error> {
+ fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> {
let (_item, wallet_data) = value;
match wallet_data {
- domain::WalletData::ApplePay(_)
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::ApplePay(_)
+ | WalletData::GooglePay(_)
+ | 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(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Square"),
))?,
}
@@ -156,31 +158,27 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::BankDebit(bank_debit_data) => {
+ PaymentMethodData::BankDebit(bank_debit_data) => {
Self::try_from((item, bank_debit_data))
}
- domain::PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
- domain::PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
- domain::PaymentMethodData::PayLater(pay_later_data) => {
- Self::try_from((item, pay_later_data))
- }
- domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?
- }
+ PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
+ PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)),
+ PaymentMethodData::PayLater(pay_later_data) => Self::try_from((item, pay_later_data)),
+ PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?,
}
}
}
@@ -191,18 +189,17 @@ pub struct SquareSessionResponse {
session_id: Secret<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
session_token: Some(item.response.session_id.clone().expose()),
- response: Ok(types::PaymentsResponseData::SessionTokenResponse {
+ response: Ok(PaymentsResponseData::SessionTokenResponse {
session_token: item.response.session_id.expose(),
}),
..item.data
@@ -215,16 +212,15 @@ pub struct SquareTokenResponse {
card_nonce: Secret<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.card_nonce.expose(),
}),
..item.data
@@ -258,13 +254,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let autocomplete = item.request.is_auto_capture()?;
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(_) => {
+ PaymentMethodData::Card(_) => {
let pm_token = item.get_payment_method_token()?;
Ok(Self {
idempotency_key: Secret::new(item.attempt_id.clone()),
source_id: match pm_token {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ PaymentMethodToken::Token(token) => token,
+ PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Square"),
)?,
},
@@ -279,26 +275,24 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
},
})
}
- domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Square"),
- ))?
- }
+ PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Square"),
+ ))?,
}
}
}
@@ -309,21 +303,21 @@ pub struct SquareAuthType {
pub(super) key1: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for SquareAuthType {
+impl TryFrom<&ConnectorAuthType> for SquareAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
}),
- types::ConnectorAuthType::HeaderKey { .. }
- | types::ConnectorAuthType::SignatureKey { .. }
- | types::ConnectorAuthType::MultiAuthKey { .. }
- | types::ConnectorAuthType::CurrencyAuthKey { .. }
- | types::ConnectorAuthType::TemporaryAuth { .. }
- | types::ConnectorAuthType::NoKey { .. }
- | types::ConnectorAuthType::CertificateAuth { .. } => {
+ ConnectorAuthType::HeaderKey { .. }
+ | ConnectorAuthType::SignatureKey { .. }
+ | ConnectorAuthType::MultiAuthKey { .. }
+ | ConnectorAuthType::CurrencyAuthKey { .. }
+ | ConnectorAuthType::TemporaryAuth { .. }
+ | ConnectorAuthType::NoKey { .. }
+ | ConnectorAuthType::CertificateAuth { .. } => {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
@@ -364,13 +358,12 @@ pub struct SquarePaymentsResponse {
payment: SquarePaymentsResponseDetails,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
//Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status.
let status = enums::AttemptStatus::from(item.response.payment.status);
@@ -380,8 +373,8 @@ impl<F, T>
};
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -448,15 +441,15 @@ pub struct RefundResponse {
refund: SquareRefundResponseDetails,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
@@ -465,15 +458,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.refund.id,
refund_status: enums::RefundStatus::from(item.response.refund.status),
}),
@@ -513,7 +504,7 @@ pub struct SquareWebhookBody {
pub data: SquareWebhookData,
}
-impl From<SquareWebhookObject> for api::IncomingWebhookEvent {
+impl From<SquareWebhookObject> for IncomingWebhookEvent {
fn from(item: SquareWebhookObject) -> Self {
match item {
SquareWebhookObject::Payment(payment_data) => match payment_data.status {
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 4c27e11fc45..5b71a1bd29c 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -12,7 +12,11 @@ pub(crate) mod headers {
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
+ pub(crate) const X_DATE: &str = "X-Date";
+ pub(crate) const X_LOGIN: &str = "X-Login";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
+ pub(crate) const X_TRANS_KEY: &str = "X-Trans-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
+ pub(crate) const X_VERSION: &str = "X-Version";
}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 31052ab0df2..0d43c263f97 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -95,6 +95,7 @@ default_imp_for_authorize_session_token!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -132,10 +133,12 @@ default_imp_for_calculate_tax!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
connectors::Stax,
+ connectors::Square,
connectors::Novalnet,
connectors::Mollie,
connectors::Nexixpay,
@@ -169,10 +172,12 @@ default_imp_for_session_update!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Mollie,
connectors::Novalnet,
@@ -208,6 +213,7 @@ default_imp_for_complete_authorize!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -216,6 +222,7 @@ default_imp_for_complete_authorize!(
connectors::Novalnet,
connectors::Nexixpay,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -245,6 +252,7 @@ default_imp_for_incremental_authorization!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -255,6 +263,7 @@ default_imp_for_incremental_authorization!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -284,6 +293,7 @@ default_imp_for_create_customer!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -293,6 +303,7 @@ default_imp_for_create_customer!(
connectors::Novalnet,
connectors::Nexixpay,
connectors::Powertranz,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -323,6 +334,7 @@ default_imp_for_connector_redirect_response!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -331,6 +343,7 @@ default_imp_for_connector_redirect_response!(
connectors::Nexixpay,
connectors::Powertranz,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -360,6 +373,7 @@ default_imp_for_pre_processing_steps!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -370,6 +384,7 @@ default_imp_for_pre_processing_steps!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -399,6 +414,7 @@ default_imp_for_post_processing_steps!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -409,6 +425,7 @@ default_imp_for_post_processing_steps!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -438,6 +455,7 @@ default_imp_for_approve!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -448,6 +466,7 @@ default_imp_for_approve!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -477,6 +496,7 @@ default_imp_for_reject!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -487,6 +507,7 @@ default_imp_for_reject!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -516,6 +537,7 @@ default_imp_for_webhook_source_verification!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -526,6 +548,7 @@ default_imp_for_webhook_source_verification!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -556,6 +579,7 @@ default_imp_for_accept_dispute!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -566,6 +590,7 @@ default_imp_for_accept_dispute!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -595,6 +620,7 @@ default_imp_for_submit_evidence!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -605,6 +631,7 @@ default_imp_for_submit_evidence!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -634,6 +661,7 @@ default_imp_for_defend_dispute!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -644,6 +672,7 @@ default_imp_for_defend_dispute!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -682,6 +711,7 @@ default_imp_for_file_upload!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -692,6 +722,7 @@ default_imp_for_file_upload!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -723,6 +754,7 @@ default_imp_for_payouts_create!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -733,6 +765,7 @@ default_imp_for_payouts_create!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -764,6 +797,7 @@ default_imp_for_payouts_retrieve!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -774,6 +808,7 @@ default_imp_for_payouts_retrieve!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -805,6 +840,7 @@ default_imp_for_payouts_eligibility!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -815,6 +851,7 @@ default_imp_for_payouts_eligibility!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -846,6 +883,7 @@ default_imp_for_payouts_fulfill!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -856,6 +894,7 @@ default_imp_for_payouts_fulfill!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -887,6 +926,7 @@ default_imp_for_payouts_cancel!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -897,6 +937,7 @@ default_imp_for_payouts_cancel!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -928,6 +969,7 @@ default_imp_for_payouts_quote!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -938,6 +980,7 @@ default_imp_for_payouts_quote!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -969,6 +1012,7 @@ default_imp_for_payouts_recipient!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -979,6 +1023,7 @@ default_imp_for_payouts_recipient!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1010,6 +1055,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1020,6 +1066,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1051,6 +1098,7 @@ default_imp_for_frm_sale!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1061,6 +1109,7 @@ default_imp_for_frm_sale!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1092,6 +1141,7 @@ default_imp_for_frm_checkout!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1102,6 +1152,7 @@ default_imp_for_frm_checkout!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1133,6 +1184,7 @@ default_imp_for_frm_transaction!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1143,6 +1195,7 @@ default_imp_for_frm_transaction!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1174,6 +1227,7 @@ default_imp_for_frm_fulfillment!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1184,6 +1238,7 @@ default_imp_for_frm_fulfillment!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1215,6 +1270,7 @@ default_imp_for_frm_record_return!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1225,6 +1281,7 @@ default_imp_for_frm_record_return!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1253,6 +1310,7 @@ default_imp_for_revoking_mandates!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1263,6 +1321,7 @@ default_imp_for_revoking_mandates!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 16e592688ac..d4e1836ac5f 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -202,6 +202,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -212,6 +213,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -242,6 +244,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -252,6 +255,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -277,6 +281,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -287,6 +292,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -318,6 +324,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -328,6 +335,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -358,6 +366,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -368,6 +377,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -398,6 +408,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -408,6 +419,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -448,6 +460,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -458,6 +471,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -490,6 +504,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -500,6 +515,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -532,6 +548,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -542,6 +559,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -574,6 +592,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -584,6 +603,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -616,6 +636,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -626,6 +647,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -658,6 +680,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -668,6 +691,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -700,6 +724,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -710,6 +735,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -742,6 +768,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -752,6 +779,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -784,6 +812,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -794,6 +823,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -824,6 +854,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -834,6 +865,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -866,6 +898,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -876,6 +909,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -908,6 +942,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -918,6 +953,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -950,6 +986,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -960,6 +997,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -992,6 +1030,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1002,6 +1041,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1034,6 +1074,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1044,6 +1085,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
@@ -1073,6 +1115,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::Deutschebank,
+ connectors::Dlocal,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -1083,6 +1126,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Powertranz,
connectors::Mollie,
connectors::Stax,
+ connectors::Square,
connectors::Taxjar,
connectors::Thunes,
connectors::Tsys,
diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs
index 3d47afb9b82..a6be862403d 100644
--- a/crates/hyperswitch_domain_models/src/types.rs
+++ b/crates/hyperswitch_domain_models/src/types.rs
@@ -1,14 +1,15 @@
use crate::{
router_data::{AccessToken, RouterData},
router_flow_types::{
- AccessTokenAuth, Authorize, CalculateTax, Capture, CompleteAuthorize,
- CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, Void,
+ AccessTokenAuth, Authorize, AuthorizeSessionToken, CalculateTax, Capture,
+ CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate,
+ Void,
},
router_request_types::{
- AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData,
- PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData,
- SetupMandateRequestData,
+ AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
+ ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData,
+ RefundsData, SetupMandateRequestData,
},
router_response_types::{
PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData,
@@ -17,6 +18,8 @@ use crate::{
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
+pub type PaymentsAuthorizeSessionTokenRouterData =
+ RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>;
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 116fc67320f..390d5de1513 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -12,7 +12,6 @@ pub mod braintree;
pub mod checkout;
pub mod cybersource;
pub mod datatrans;
-pub mod dlocal;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
@@ -46,7 +45,6 @@ pub mod razorpay;
pub mod riskified;
pub mod shift4;
pub mod signifyd;
-pub mod square;
pub mod stripe;
pub mod threedsecureio;
pub mod trustpay;
@@ -61,11 +59,11 @@ pub mod zsl;
pub use hyperswitch_connectors::connectors::{
bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
- deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
- fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie,
- nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
- stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt,
- volt::Volt, worldline, worldline::Worldline,
+ deutschebank::Deutschebank, dlocal, dlocal::Dlocal, fiserv, fiserv::Fiserv, fiservemea,
+ fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim,
+ mollie, mollie::Mollie, nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz,
+ powertranz::Powertranz, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar,
+ thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -74,14 +72,13 @@ pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
- cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
+ cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo,
opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone,
paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, prophetpay::Prophetpay,
rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd,
- square::Square, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay,
- wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay,
- zen::Zen, zsl::Zsl,
+ stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargo::Wellsfargo,
+ wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, zen::Zen, zsl::Zsl,
};
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 3ff93cf9bf0..5c350f3a475 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -685,7 +685,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -715,7 +714,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -760,7 +758,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -790,7 +787,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -829,7 +825,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -859,7 +854,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -920,7 +914,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -950,7 +943,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -993,7 +985,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1023,7 +1014,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1050,7 +1040,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1080,7 +1069,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1134,7 +1122,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1164,7 +1151,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1297,7 +1283,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1327,7 +1312,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1373,7 +1357,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1403,7 +1386,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1449,7 +1431,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1479,7 +1460,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1525,7 +1505,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1555,7 +1534,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1601,7 +1579,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1631,7 +1608,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1677,7 +1653,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1707,7 +1682,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1753,7 +1727,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1784,7 +1757,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1829,7 +1801,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1859,7 +1830,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -1903,7 +1873,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1933,7 +1902,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2066,7 +2034,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2096,7 +2063,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2142,7 +2108,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2172,7 +2137,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2218,7 +2182,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2248,7 +2211,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2294,7 +2256,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2324,7 +2285,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2370,7 +2330,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2400,7 +2359,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
@@ -2443,7 +2401,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2473,7 +2430,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Trustpay,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 79ed9e25259..677c7968f45 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -211,7 +211,6 @@ default_imp_for_complete_authorize!(
connector::Boku,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Gocardless,
@@ -235,7 +234,6 @@ default_imp_for_complete_authorize!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -287,7 +285,6 @@ default_imp_for_webhook_source_verification!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -318,7 +315,6 @@ default_imp_for_webhook_source_verification!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -372,7 +368,6 @@ default_imp_for_create_customer!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -403,7 +398,6 @@ default_imp_for_create_customer!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Trustpay,
connector::Wellsfargo,
@@ -453,7 +447,6 @@ default_imp_for_connector_redirect_response!(
connector::Boku,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Gocardless,
@@ -478,7 +471,6 @@ default_imp_for_connector_redirect_response!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Wellsfargo,
connector::Wellsfargopayout,
@@ -618,7 +610,6 @@ default_imp_for_accept_dispute!(
connector::Braintree,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -650,7 +641,6 @@ default_imp_for_accept_dispute!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -724,7 +714,6 @@ default_imp_for_file_upload!(
connector::Braintree,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -755,7 +744,6 @@ default_imp_for_file_upload!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Trustpay,
connector::Opennode,
@@ -807,7 +795,6 @@ default_imp_for_submit_evidence!(
connector::Braintree,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -838,7 +825,6 @@ default_imp_for_submit_evidence!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Trustpay,
connector::Opennode,
@@ -890,7 +876,6 @@ default_imp_for_defend_dispute!(
connector::Braintree,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Globalpay,
connector::Forte,
@@ -921,7 +906,6 @@ default_imp_for_defend_dispute!(
connector::Riskified,
connector::Shift4,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
@@ -988,7 +972,6 @@ default_imp_for_pre_processing_steps!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
@@ -1014,7 +997,6 @@ default_imp_for_pre_processing_steps!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Wellsfargo,
connector::Wellsfargopayout,
@@ -1059,7 +1041,6 @@ default_imp_for_post_processing_steps!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Iatapay,
connector::Itaubank,
@@ -1083,7 +1064,6 @@ default_imp_for_post_processing_steps!(
connector::Rapyd,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Threedsecureio,
connector::Wellsfargo,
connector::Wellsfargopayout,
@@ -1218,7 +1198,6 @@ default_imp_for_payouts_create!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1247,7 +1226,6 @@ default_imp_for_payouts_create!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1301,7 +1279,6 @@ default_imp_for_payouts_retrieve!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1332,7 +1309,6 @@ default_imp_for_payouts_retrieve!(
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1389,7 +1365,6 @@ default_imp_for_payouts_eligibility!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1419,7 +1394,6 @@ default_imp_for_payouts_eligibility!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -1471,7 +1445,6 @@ default_imp_for_payouts_fulfill!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1499,7 +1472,6 @@ default_imp_for_payouts_fulfill!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1552,7 +1524,6 @@ default_imp_for_payouts_cancel!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1582,7 +1553,6 @@ default_imp_for_payouts_cancel!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1636,7 +1606,6 @@ default_imp_for_payouts_quote!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1666,7 +1635,6 @@ default_imp_for_payouts_quote!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -1721,7 +1689,6 @@ default_imp_for_payouts_recipient!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Forte,
connector::Globalpay,
connector::Gocardless,
@@ -1751,7 +1718,6 @@ default_imp_for_payouts_recipient!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1808,7 +1774,6 @@ default_imp_for_payouts_recipient_account!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1839,7 +1804,6 @@ default_imp_for_payouts_recipient_account!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Shift4,
connector::Threedsecureio,
connector::Trustpay,
@@ -1893,7 +1857,6 @@ default_imp_for_approve!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -1924,7 +1887,6 @@ default_imp_for_approve!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -1979,7 +1941,6 @@ default_imp_for_reject!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2010,7 +1971,6 @@ default_imp_for_reject!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2155,7 +2115,6 @@ default_imp_for_frm_sale!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2184,7 +2143,6 @@ default_imp_for_frm_sale!(
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2241,7 +2199,6 @@ default_imp_for_frm_checkout!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2270,7 +2227,6 @@ default_imp_for_frm_checkout!(
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2327,7 +2283,6 @@ default_imp_for_frm_transaction!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2356,7 +2311,6 @@ default_imp_for_frm_transaction!(
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2413,7 +2367,6 @@ default_imp_for_frm_fulfillment!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2442,7 +2395,6 @@ default_imp_for_frm_fulfillment!(
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2499,7 +2451,6 @@ default_imp_for_frm_record_return!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2528,7 +2479,6 @@ default_imp_for_frm_record_return!(
connector::Prophetpay,
connector::Rapyd,
connector::Razorpay,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2582,7 +2532,6 @@ default_imp_for_incremental_authorization!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2613,7 +2562,6 @@ default_imp_for_incremental_authorization!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2664,7 +2612,6 @@ default_imp_for_revoking_mandates!(
connector::Braintree,
connector::Checkout,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2694,7 +2641,6 @@ default_imp_for_revoking_mandates!(
connector::Razorpay,
connector::Riskified,
connector::Signifyd,
- connector::Square,
connector::Stripe,
connector::Shift4,
connector::Threedsecureio,
@@ -2906,7 +2852,6 @@ default_imp_for_authorize_session_token!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -2988,7 +2933,6 @@ default_imp_for_calculate_tax!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -3018,7 +2962,6 @@ default_imp_for_calculate_tax!(
connector::Rapyd,
connector::Razorpay,
connector::Riskified,
- connector::Square,
connector::Signifyd,
connector::Stripe,
connector::Shift4,
@@ -3072,7 +3015,6 @@ default_imp_for_session_update!(
connector::Checkout,
connector::Cybersource,
connector::Datatrans,
- connector::Dlocal,
connector::Ebanx,
connector::Forte,
connector::Globalpay,
@@ -3102,7 +3044,6 @@ default_imp_for_session_update!(
connector::Rapyd,
connector::Razorpay,
connector::Riskified,
- connector::Square,
connector::Signifyd,
connector::Stripe,
connector::Shift4,
| 2024-09-30T08:36:17Z |
## Description
Move conector Dlocal and Square from router to hyperswitch_connector crate
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1727684785",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "https://www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "food"
}
]
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1727684450' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"name": "API Key 1",
"description": null,
"expiration": "2038-01-19T03:14:08.000Z"
}'
```
3. Create Payment Connector for Dlocal
```
curl --location 'http://localhost:8080/account/merchant_1727684450/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "dlocal",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "_____",
"key1": "_____",
"api_secret" : "_____"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245",
"brand_id": "001",
"destination_account_number": "5001000001223369"
},
"business_country": "US",
"business_label": "food"
}'
```
4. Payment Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ______' \
--data-raw '{
"amount": 60000,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2024-09-10T10:11:12Z",
"amount_to_capture": 60000,
"customer_id": "jsdhfgbds",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "02",
"card_exp_year": "37",
"card_holder_name": "joseph Doe",
"card_cvc": "999"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "dlocal"
}
}'
```
5. Response
```
{
"payment_id": "pay_2cRAibQolK8jdZr1Teai",
"merchant_id": "merchant_1727684450",
"status": "succeeded",
"amount": 60000,
"net_amount": 60000,
"amount_capturable": 0,
"amount_received": 60000,
"connector": "dlocal",
"client_secret": "pay_2cRAibQolK8jdZr1Teai_secret_tINYaNt6LoYfuq2wD2Am",
"created": "2024-09-30T08:20:54.759Z",
"currency": "BRL",
"customer_id": "jsdhfgbds",
"customer": {
"id": "jsdhfgbds",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "02",
"card_exp_year": "37",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "jsdhfgbds",
"created_at": 1727684454,
"expires": 1727688054,
"secret": "epk_ed5899814cc94112940d95f020cdb9aa"
},
"manual_retry_allowed": false,
"connector_transaction_id": "T-413100-f19a6e86-e95d-4e9e-bb5c-e27371ae8aa0",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_2cRAibQolK8jdZr1Teai_1",
"payment_link": null,
"profile_id": "pro_9mhY0ulaJuedDbQRGBDi",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_x0MV7McpNzabX1vANWza",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-30T08:35:54.759Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-30T08:20:56.357Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | dcec2a2bff082b606cc3376e9451d53ed6ecdf04 | 1. Create Merchant Account
```
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "merchant_1727684785",
"locker_id": "m0010",
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "https://www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"return_url": "https://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "food"
}
]
}'
```
2. Create API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1727684450' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"name": "API Key 1",
"description": null,
"expiration": "2038-01-19T03:14:08.000Z"
}'
```
3. Create Payment Connector for Dlocal
```
curl --location 'http://localhost:8080/account/merchant_1727684450/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "dlocal",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "_____",
"key1": "_____",
"api_secret" : "_____"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245",
"brand_id": "001",
"destination_account_number": "5001000001223369"
},
"business_country": "US",
"business_label": "food"
}'
```
4. Payment Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ______' \
--data-raw '{
"amount": 60000,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2024-09-10T10:11:12Z",
"amount_to_capture": 60000,
"customer_id": "jsdhfgbds",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "02",
"card_exp_year": "37",
"card_holder_name": "joseph Doe",
"card_cvc": "999"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "BR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "dlocal"
}
}'
```
5. Response
```
{
"payment_id": "pay_2cRAibQolK8jdZr1Teai",
"merchant_id": "merchant_1727684450",
"status": "succeeded",
"amount": 60000,
"net_amount": 60000,
"amount_capturable": 0,
"amount_received": 60000,
"connector": "dlocal",
"client_secret": "pay_2cRAibQolK8jdZr1Teai_secret_tINYaNt6LoYfuq2wD2Am",
"created": "2024-09-30T08:20:54.759Z",
"currency": "BRL",
"customer_id": "jsdhfgbds",
"customer": {
"id": "jsdhfgbds",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "02",
"card_exp_year": "37",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "BR",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "jsdhfgbds",
"created_at": 1727684454,
"expires": 1727688054,
"secret": "epk_ed5899814cc94112940d95f020cdb9aa"
},
"manual_retry_allowed": false,
"connector_transaction_id": "T-413100-f19a6e86-e95d-4e9e-bb5c-e27371ae8aa0",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_2cRAibQolK8jdZr1Teai_1",
"payment_link": null,
"profile_id": "pro_9mhY0ulaJuedDbQRGBDi",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_x0MV7McpNzabX1vANWza",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-30T08:35:54.759Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-30T08:20:56.357Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
| [
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/dlocal.rs",
"crates/router/src/connector/dlocal/transformers.rs",
"crates/router/src/connector/square.rs",
"crates/router/src/connector/square/transformers.rs",
"crates/hyperswitch_connectors/src/constants.rs",
"crates/hyper... | |
juspay/hyperswitch | juspay__hyperswitch-6146 | Bug: fix(user_roles): Send only same and below Entity Level Users in List Users API
Currently in user list api, for merchants we show org admin.
This is happening because in V1 data, we have merchant_id in org level users as well, because of why the filtering is not correct. | diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b841f88eca1..e10fa0eb81c 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -736,6 +736,16 @@ pub async fn list_users_in_lineage(
}
};
+ // This filtering is needed because for org level users in V1, merchant_id is present.
+ // Due to this, we get org level users in merchant level users list.
+ let user_roles_set = user_roles_set
+ .into_iter()
+ .filter_map(|user_role| {
+ let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
+ (entity_type <= requestor_role_info.get_entity_type()).then_some(user_role)
+ })
+ .collect::<HashSet<_>>();
+
let mut email_map = state
.global_store
.find_users_by_user_ids(
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index f2aae68fcbc..b6db8340775 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,4 +1,4 @@
-use std::collections::HashSet;
+use std::{cmp, collections::HashSet};
use api_models::user_role as user_role_api;
use common_enums::{EntityType, PermissionGroup};
@@ -418,28 +418,16 @@ pub fn get_min_entity(
user_entity: EntityType,
filter_entity: Option<EntityType>,
) -> UserResult<EntityType> {
- match (user_entity, filter_entity) {
- (EntityType::Organization, None)
- | (EntityType::Organization, Some(EntityType::Organization)) => {
- Ok(EntityType::Organization)
- }
+ let Some(filter_entity) = filter_entity else {
+ return Ok(user_entity);
+ };
- (EntityType::Merchant, None)
- | (EntityType::Organization, Some(EntityType::Merchant))
- | (EntityType::Merchant, Some(EntityType::Merchant)) => Ok(EntityType::Merchant),
-
- (EntityType::Profile, None)
- | (EntityType::Organization, Some(EntityType::Profile))
- | (EntityType::Merchant, Some(EntityType::Profile))
- | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile),
-
- (EntityType::Merchant, Some(EntityType::Organization))
- | (EntityType::Profile, Some(EntityType::Organization))
- | (EntityType::Profile, Some(EntityType::Merchant)) => {
- Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
- "{} level user requesting data for {:?} level",
- user_entity, filter_entity
- ))
- }
+ if user_entity < filter_entity {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "{} level user requesting data for {:?} level",
+ user_entity, filter_entity
+ ));
}
+
+ Ok(cmp::min(user_entity, filter_entity))
}
| 2024-09-27T11:56:42Z |
## Description
<!-- Describe your changes in detail -->
- Send only same and below Entity Level Users in List Users API.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes [#6146](https://github.com/juspay/hyperswitch/issues/6146).
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
This API when called with merchant level users, it should not send org level users in response. Can be tested via control center. | 67d6d2247bb53dc25831d65305269ba6889c99de |
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
This API when called with merchant level users, it should not send org level users in response. Can be tested via control center.
| [
"crates/router/src/core/user_role.rs",
"crates/router/src/utils/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6141 | Bug: fix(admin): jwt added for organization update and retrieve
Previously, updating and retrieving organization details required authentication using the admin API key. With the recent change, the dashboard JWT can now be used to update the org_name directly through the dashboard. | diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index e5a18fba536..78238d3af07 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -39,14 +39,24 @@ pub async fn organization_update(
) -> HttpResponse {
let flow = Flow::OrganizationUpdate;
let organization_id = org_id.into_inner();
- let org_id = admin::OrganizationId { organization_id };
+ let org_id = admin::OrganizationId {
+ organization_id: organization_id.clone(),
+ };
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| update_organization(state, org_id.clone(), req),
- &auth::AdminApiAuth,
+ auth::auth_type(
+ &auth::AdminApiAuth,
+ &auth::JWTAuthOrganizationFromRoute {
+ organization_id,
+ required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Organization,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -61,14 +71,25 @@ pub async fn organization_retrieve(
) -> HttpResponse {
let flow = Flow::OrganizationRetrieve;
let organization_id = org_id.into_inner();
- let payload = admin::OrganizationId { organization_id };
+ let payload = admin::OrganizationId {
+ organization_id: organization_id.clone(),
+ };
+
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, req, _| get_organization(state, req),
- &auth::AdminApiAuth,
+ auth::auth_type(
+ &auth::AdminApiAuth,
+ &auth::JWTAuthOrganizationFromRoute {
+ organization_id,
+ required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Organization,
+ },
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index d8318ce9517..225d6a783fc 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -88,6 +88,10 @@ pub enum AuthenticationType {
AdminApiAuthWithMerchantId {
merchant_id: id_type::MerchantId,
},
+ OrganizationJwt {
+ org_id: id_type::OrganizationId,
+ user_id: String,
+ },
MerchantJwt {
merchant_id: id_type::MerchantId,
user_id: Option<String>,
@@ -149,6 +153,7 @@ impl AuthenticationType {
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id } => Some(merchant_id),
Self::AdminApiKey
+ | Self::OrganizationJwt { .. }
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
| Self::SinglePurposeOrLoginJwt { .. }
@@ -1134,6 +1139,45 @@ where
}
}
+pub struct JWTAuthOrganizationFromRoute {
+ pub organization_id: id_type::OrganizationId,
+ pub required_permission: Permission,
+ pub minimum_entity_level: EntityType,
+}
+
+#[async_trait]
+impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<((), AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
+ // Check if token has access to Organization that has been requested in the route
+ if payload.org_id != self.organization_id {
+ return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
+ }
+ Ok((
+ (),
+ AuthenticationType::OrganizationJwt {
+ org_id: payload.org_id,
+ user_id: payload.user_id,
+ },
+ ))
+ }
+}
+
pub struct JWTAuthMerchantFromRoute {
pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
| 2024-09-27T07:14:54Z |
## Description
<!-- Describe your changes in detail -->
Previously, updating and retrieving organization details required authentication using the admin API key. With the recent change, the dashboard JWT can now be used to update the org_name directly through the dashboard.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #6141
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request :
```
curl --location --request PUT 'http://localhost:8080/organization/${org_id}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"organization_name":"RiddhiTest3"
}'
```
Response:
```
{
"organization_id": "org_id",
"organization_name": "RiddhiTest3",
"organization_details": null,
"metadata": null,
"modified_at": "2024-09-27 07:13:13.074956",
"created_at": "2024-09-19 12:46:25.990045"
}
```
Request :
```
curl --location 'http://localhost:8080/organization/${org_id}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response:
```
{
"organization_id": "org_id",
"organization_name": "RiddhiTest3",
"organization_details": null,
"metadata": null,
"modified_at": "2024-09-27 07:13:13.074956",
"created_at": "2024-09-19 12:46:25.990045"
}
``` | 67d6d2247bb53dc25831d65305269ba6889c99de |
Request :
```
curl --location --request PUT 'http://localhost:8080/organization/${org_id}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"organization_name":"RiddhiTest3"
}'
```
Response:
```
{
"organization_id": "org_id",
"organization_name": "RiddhiTest3",
"organization_details": null,
"metadata": null,
"modified_at": "2024-09-27 07:13:13.074956",
"created_at": "2024-09-19 12:46:25.990045"
}
```
Request :
```
curl --location 'http://localhost:8080/organization/${org_id}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response:
```
{
"organization_id": "org_id",
"organization_name": "RiddhiTest3",
"organization_details": null,
"metadata": null,
"modified_at": "2024-09-27 07:13:13.074956",
"created_at": "2024-09-19 12:46:25.990045"
}
```
| [
"crates/router/src/routes/admin.rs",
"crates/router/src/services/authentication.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-8556 | Bug: [FEATURE] Add auto retries configs in profile CRUD apis
### Feature Description
Add auto retries configs in profile CRUD apis
1. is_auto_retries_enabled - Boolean (denotes whether auto retries should be performed for a profile)
2. max_auto_retries_enabled - Int (i16) (maximum auto retries to be performed)
### Possible Implementation
Create two new fields in Profile Create, Update APIs and then send them back in the Profile Response | diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 6f656339569..6e7f4f29d03 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1971,6 +1971,12 @@ pub struct ProfileCreate {
/// If set to `true` is_network_tokenization_enabled will be checked.
#[serde(default)]
pub is_network_tokenization_enabled: bool,
+
+ /// Indicates if is_auto_retries_enabled is enabled or not.
+ pub is_auto_retries_enabled: Option<bool>,
+
+ /// Maximum number of auto retries allowed for a payment
+ pub max_auto_retries_enabled: Option<u8>,
}
#[nutype::nutype(
@@ -2202,6 +2208,13 @@ pub struct ProfileResponse {
/// If set to `true` is_network_tokenization_enabled will be checked.
#[schema(default = false, example = false)]
pub is_network_tokenization_enabled: bool,
+
+ /// Indicates if is_auto_retries_enabled is enabled or not.
+ #[schema(default = false, example = false)]
+ pub is_auto_retries_enabled: bool,
+
+ /// Maximum number of auto retries allowed for a payment
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v2")]
@@ -2431,6 +2444,12 @@ pub struct ProfileUpdate {
/// Indicates if is_network_tokenization_enabled is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
+
+ /// Indicates if is_auto_retries_enabled is enabled or not.
+ pub is_auto_retries_enabled: Option<bool>,
+
+ /// Maximum number of auto retries allowed for a payment
+ pub max_auto_retries_enabled: Option<u8>,
}
#[cfg(feature = "v2")]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 4edc2ba2432..fd0abc16614 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -55,6 +55,8 @@ pub struct Profile {
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -96,6 +98,8 @@ pub struct ProfileNew {
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -134,6 +138,8 @@ pub struct ProfileUpdateInternal {
pub is_tax_connector_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -171,6 +177,8 @@ impl ProfileUpdateInternal {
is_tax_connector_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
+ is_auto_retries_enabled,
+ max_auto_retries_enabled,
} = self;
Profile {
profile_id: source.profile_id,
@@ -228,6 +236,8 @@ impl ProfileUpdateInternal {
.or(source.dynamic_routing_algorithm),
is_network_tokenization_enabled: is_network_tokenization_enabled
.unwrap_or(source.is_network_tokenization_enabled),
+ is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
+ max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
}
}
}
@@ -279,6 +289,8 @@ pub struct Profile {
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
impl Profile {
@@ -334,6 +346,8 @@ pub struct ProfileNew {
pub id: common_utils::id_type::ProfileId,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v2")]
@@ -373,6 +387,8 @@ pub struct ProfileUpdateInternal {
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub is_network_tokenization_enabled: Option<bool>,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v2")]
@@ -411,6 +427,8 @@ impl ProfileUpdateInternal {
payout_routing_algorithm_id,
default_fallback_routing,
is_network_tokenization_enabled,
+ is_auto_retries_enabled,
+ max_auto_retries_enabled,
} = self;
Profile {
id: source.id,
@@ -471,6 +489,8 @@ impl ProfileUpdateInternal {
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: is_network_tokenization_enabled
.unwrap_or(source.is_network_tokenization_enabled),
+ is_auto_retries_enabled: is_auto_retries_enabled.or(source.is_auto_retries_enabled),
+ max_auto_retries_enabled: max_auto_retries_enabled.or(source.max_auto_retries_enabled),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9ff7c958df1..fe22dcd87a3 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -211,6 +211,8 @@ diesel::table! {
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
+ is_auto_retries_enabled -> Nullable<Bool>,
+ max_auto_retries_enabled -> Nullable<Int2>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index a66286e02db..674123fbaae 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -218,6 +218,8 @@ diesel::table! {
version -> ApiVersion,
dynamic_routing_algorithm -> Nullable<Json>,
is_network_tokenization_enabled -> Bool,
+ is_auto_retries_enabled -> Nullable<Bool>,
+ max_auto_retries_enabled -> Nullable<Int2>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index 156ca4d2feb..75cdd40024f 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -56,6 +56,8 @@ pub struct Profile {
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: bool,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -94,6 +96,8 @@ pub struct ProfileSetter {
pub is_tax_connector_enabled: bool,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
+ pub is_auto_retries_enabled: bool,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -139,6 +143,8 @@ impl From<ProfileSetter> for Profile {
version: consts::API_VERSION,
dynamic_routing_algorithm: value.dynamic_routing_algorithm,
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
+ is_auto_retries_enabled: value.is_auto_retries_enabled,
+ max_auto_retries_enabled: value.max_auto_retries_enabled,
}
}
}
@@ -186,6 +192,8 @@ pub struct ProfileGeneralUpdate {
pub is_tax_connector_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
+ pub is_auto_retries_enabled: Option<bool>,
+ pub max_auto_retries_enabled: Option<i16>,
}
#[cfg(feature = "v1")]
@@ -246,6 +254,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
+ is_auto_retries_enabled,
+ max_auto_retries_enabled,
} = *update;
Self {
@@ -281,6 +291,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
+ is_auto_retries_enabled,
+ max_auto_retries_enabled,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
@@ -318,6 +330,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm,
@@ -353,6 +367,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled: None,
dynamic_routing_algorithm,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -388,6 +404,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -423,6 +441,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
@@ -458,6 +478,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
}
}
@@ -512,6 +534,8 @@ impl super::behaviour::Conversion for Profile {
version: self.version,
dynamic_routing_algorithm: self.dynamic_routing_algorithm,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
+ max_auto_retries_enabled: self.max_auto_retries_enabled,
})
}
@@ -578,6 +602,8 @@ impl super::behaviour::Conversion for Profile {
version: item.version,
dynamic_routing_algorithm: item.dynamic_routing_algorithm,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
+ is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false),
+ max_auto_retries_enabled: item.max_auto_retries_enabled,
})
}
.await
@@ -628,6 +654,8 @@ impl super::behaviour::Conversion for Profile {
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
+ max_auto_retries_enabled: self.max_auto_retries_enabled,
})
}
}
@@ -896,6 +924,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
@@ -934,6 +964,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -970,6 +1002,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -1006,6 +1040,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::DefaultRoutingFallbackUpdate {
default_fallback_routing,
@@ -1042,6 +1078,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
@@ -1078,6 +1116,8 @@ impl From<ProfileUpdate> for ProfileUpdateInternal {
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
},
}
}
@@ -1134,6 +1174,8 @@ impl super::behaviour::Conversion for Profile {
version: self.version,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
})
}
@@ -1253,6 +1295,8 @@ impl super::behaviour::Conversion for Profile {
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: None,
+ max_auto_retries_enabled: None,
})
}
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index ad9925a241f..d27b6b82fd4 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3537,6 +3537,8 @@ impl ProfileCreateBridge for api::ProfileCreate {
.always_collect_shipping_details_from_wallet_connector,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(),
+ max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
}))
}
@@ -3884,6 +3886,8 @@ impl ProfileUpdateBridge for api::ProfileUpdate {
is_tax_connector_enabled: self.is_tax_connector_enabled,
dynamic_routing_algorithm: self.dynamic_routing_algorithm,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
+ is_auto_retries_enabled: self.is_auto_retries_enabled,
+ max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
},
)))
}
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index c7b76d1780a..8d52e5dc11a 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -168,6 +168,8 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse {
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
+ is_auto_retries_enabled: item.is_auto_retries_enabled,
+ max_auto_retries_enabled: item.max_auto_retries_enabled,
})
}
}
@@ -353,5 +355,7 @@ pub async fn create_profile_from_merchant_account(
is_tax_connector_enabled: request.is_tax_connector_enabled,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: request.is_network_tokenization_enabled,
+ is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(),
+ max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from),
}))
}
diff --git a/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/down.sql b/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/down.sql
new file mode 100644
index 00000000000..3751f25da4b
--- /dev/null
+++ b/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+-- Drop is_auto_retries_enabled column from business_profile table
+ALTER TABLE business_profile DROP COLUMN IF EXISTS is_auto_retries_enabled;
+
+-- Drop max_auto_retries_enabled column from business_profile table
+ALTER TABLE business_profile DROP COLUMN IF EXISTS max_auto_retries_enabled;
diff --git a/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/up.sql b/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/up.sql
new file mode 100644
index 00000000000..05b6a114a31
--- /dev/null
+++ b/migrations/2024-09-26-113912_add-auto-retries-configs-in-profile/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+-- Add is_auto_retries_enabled column in business_profile table
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_auto_retries_enabled BOOLEAN;
+
+-- Add max_auto_retries_enabled column in business_profile table
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS max_auto_retries_enabled SMALLINT;
| 2024-09-26T17:43:50Z |
## Description
<!-- Describe your changes in detail -->
add auto retries configs in profile CRUD apis
1. is_auto_retries_enabled - Boolean (denotes whether auto retries should be performed for a profile)
2. max_auto_retries_enabled - Int (maximum auto retries to be performed)
closes - https://github.com/juspay/hyperswitch/issues/8556
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
4. `crates/router/src/configs`
5. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested Manually
1. Profile Create
```
curl --location '{{BASE_URL}}/account/{{MERCHANT_ID}}/business_profile' \
--header 'Content-Type: application/json' \
--header 'api-key: {{ADMIN_API_KEY}}' \
--data '{
"is_auto_retries_enabled": true,
"max_auto_retries_enabled": 1
}'
```
Response
`{
"merchant_id": "merchant_1727371477",
"profile_id": "pro_jIc12oz9zLreWO4gJqXZ",
"profile_name": "default",
"return_url": "https://example.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "uskD31l0vpyRXItGriQ2FZvyhgNJvY5eo3rpy7mnJ0iqm0ExGMgenVstuaVaTxtI",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://eop67yav2axa2pv.m.pipedream.net/",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false,
"is_auto_retries_enabled": true,
"max_auto_retries_enabled": 1
}`
2. Profile Update
```
curl --location '{{BASE_URL}}/account/{{MERCHANT_ID}}/business_profile/{{PROFILE_ID}}' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{ADMIN_API_KEY}}' \
--data '{
"is_auto_retries_enabled": false,
"max_auto_retries_enabled": 2
}'
```
Response:
`{
"merchant_id": "merchant_1727371477",
"profile_id": "pro_jIc12oz9zLreWO4gJqXZ",
"profile_name": "default",
"return_url": "https://example.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "uskD31l0vpyRXItGriQ2FZvyhgNJvY5eo3rpy7mnJ0iqm0ExGMgenVstuaVaTxtI",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://eop67yav2axa2pv.m.pipedream.net/",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false,
"is_auto_retries_enabled": false,
"max_auto_retries_enabled": 2
}` | 5912936f9f2178f002c96e25636b25f532b1ecb2 |
Tested Manually
1. Profile Create
```
curl --location '{{BASE_URL}}/account/{{MERCHANT_ID}}/business_profile' \
--header 'Content-Type: application/json' \
--header 'api-key: {{ADMIN_API_KEY}}' \
--data '{
"is_auto_retries_enabled": true,
"max_auto_retries_enabled": 1
}'
```
Response
`{
"merchant_id": "merchant_1727371477",
"profile_id": "pro_jIc12oz9zLreWO4gJqXZ",
"profile_name": "default",
"return_url": "https://example.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "uskD31l0vpyRXItGriQ2FZvyhgNJvY5eo3rpy7mnJ0iqm0ExGMgenVstuaVaTxtI",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://eop67yav2axa2pv.m.pipedream.net/",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false,
"is_auto_retries_enabled": true,
"max_auto_retries_enabled": 1
}`
2. Profile Update
```
curl --location '{{BASE_URL}}/account/{{MERCHANT_ID}}/business_profile/{{PROFILE_ID}}' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{ADMIN_API_KEY}}' \
--data '{
"is_auto_retries_enabled": false,
"max_auto_retries_enabled": 2
}'
```
Response:
`{
"merchant_id": "merchant_1727371477",
"profile_id": "pro_jIc12oz9zLreWO4gJqXZ",
"profile_name": "default",
"return_url": "https://example.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "uskD31l0vpyRXItGriQ2FZvyhgNJvY5eo3rpy7mnJ0iqm0ExGMgenVstuaVaTxtI",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": "https://eop67yav2axa2pv.m.pipedream.net/",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false,
"is_auto_retries_enabled": false,
"max_auto_retries_enabled": 2
}`
| [
"crates/api_models/src/admin.rs",
"crates/diesel_models/src/business_profile.rs",
"crates/diesel_models/src/schema.rs",
"crates/diesel_models/src/schema_v2.rs",
"crates/hyperswitch_domain_models/src/business_profile.rs",
"crates/router/src/core/admin.rs",
"crates/router/src/types/api/admin.rs",
"migra... | |
juspay/hyperswitch | juspay__hyperswitch-6112 | Bug: refactor(users): Deprecate non-profile level user APIs
- Currently there are few APIs in Backend which are not at profile level. For example - Switch merchant.
- We have to remove those APIs.
- If there is any v2 counter part for those APIs, v1 APIs should be modified so that they will work the same way as v1. | diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 9b100a7321e..bb61a025180 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -12,25 +12,16 @@ use crate::user::{
},
AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse,
ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,
- CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,
- GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, GetUserRoleDetailsResponseV2,
- InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
- TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest,
- UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest,
+ GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponseV2, InviteUserRequest, ReInviteUserRequest, RecoveryCodes,
+ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest,
+ SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest,
+ SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse,
+ UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
+ UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
-impl ApiEventMetric for DashboardEntryResponse {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::User {
- user_id: self.user_id.clone(),
- })
- }
-}
-
#[cfg(feature = "recon")]
impl ApiEventMetric for VerifyTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -55,7 +46,6 @@ common_utils::impl_api_event_type!(
SwitchProfileRequest,
CreateInternalUserRequest,
UserMerchantCreate,
- ListUsersResponse,
AuthorizeResponse,
ConnectAccountRequest,
ForgotPasswordRequest,
@@ -69,7 +59,6 @@ common_utils::impl_api_event_type!(
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
GetUserRoleDetailsRequest,
- GetUserRoleDetailsResponse,
GetUserRoleDetailsResponseV2,
TokenResponse,
TwoFactorAuthStatusResponse,
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index eb09abd471c..a2c76ecc394 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -3,26 +3,21 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest,
- ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse,
- RoleInfoWithPermissionsResponse, UpdateRoleRequest,
+ RoleInfoResponseNew, RoleInfoWithGroupsResponse, UpdateRoleRequest,
},
- AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest,
+ AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest,
+ UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
Miscellaneous,
(
- RoleInfoWithPermissionsResponse,
GetRoleRequest,
AuthorizationInfoResponse,
UpdateUserRoleRequest,
- MerchantSelectRequest,
- AcceptInvitationRequest,
DeleteUserRoleRequest,
CreateRoleRequest,
UpdateRoleRequest,
- ListRolesResponse,
ListRolesAtEntityLevelRequest,
RoleInfoResponseNew,
RoleInfoWithGroupsResponse,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7b22387b3c3..d66f9f3bc03 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose};
+use common_enums::{EntityType, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
@@ -25,19 +25,6 @@ pub struct SignUpRequest {
pub password: Secret<String>,
}
-#[derive(serde::Serialize, Debug, Clone)]
-pub struct DashboardEntryResponse {
- pub token: Secret<String>,
- pub merchant_id: id_type::MerchantId,
- pub name: Secret<String>,
- pub email: pii::Email,
- pub verification_days_left: Option<i64>,
- pub user_role: String,
- //this field is added for audit/debug reasons
- #[serde(skip_serializing)]
- pub user_id: String,
-}
-
pub type SignInRequest = SignUpRequest;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
@@ -131,20 +118,6 @@ pub struct UserMerchantCreate {
pub company_name: String,
}
-#[derive(Debug, serde::Serialize)]
-pub struct ListUsersResponse(pub Vec<UserDetails>);
-
-#[derive(Debug, serde::Serialize)]
-pub struct UserDetails {
- pub email: pii::Email,
- pub name: Secret<String>,
- pub role_id: String,
- pub role_name: String,
- pub status: UserStatus,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub last_modified_at: time::PrimitiveDateTime,
-}
-
#[derive(serde::Serialize, Debug, Clone)]
pub struct GetUserDetailsResponse {
pub merchant_id: id_type::MerchantId,
@@ -167,19 +140,6 @@ pub struct GetUserRoleDetailsRequest {
pub email: pii::Email,
}
-#[derive(Debug, serde::Serialize)]
-pub struct GetUserRoleDetailsResponse {
- pub email: pii::Email,
- pub name: Secret<String>,
- pub role_id: String,
- pub role_name: String,
- pub status: UserStatus,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub last_modified_at: time::PrimitiveDateTime,
- pub groups: Vec<PermissionGroup>,
- pub role_scope: RoleScope,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct GetUserRoleDetailsResponseV2 {
pub role_id: String,
@@ -207,16 +167,6 @@ pub struct SendVerifyEmailRequest {
pub email: pii::Email,
}
-#[derive(Debug, serde::Serialize)]
-pub struct UserMerchantAccount {
- pub merchant_id: id_type::MerchantId,
- pub merchant_name: OptionalEncryptableName,
- pub is_active: bool,
- pub role_id: String,
- pub role_name: String,
- pub org_id: id_type::OrganizationId,
-}
-
#[cfg(feature = "recon")]
#[derive(serde::Serialize, Debug)]
pub struct VerifyTokenResponse {
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index f2743d6a311..ab32651e729 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -54,42 +54,17 @@ pub enum ParentGroup {
Recon,
}
-#[derive(Debug, serde::Serialize)]
-pub enum PermissionModule {
- Payments,
- Refunds,
- MerchantAccount,
- Connectors,
- Routing,
- Analytics,
- Mandates,
- Customer,
- Disputes,
- ThreeDsDecisionManager,
- SurchargeDecisionManager,
- AccountCreate,
- Payouts,
- Recon,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum AuthorizationInfo {
- Module(ModuleInfo),
Group(GroupInfo),
GroupWithTag(ParentInfo),
}
-#[derive(Debug, serde::Serialize)]
-pub struct ModuleInfo {
- pub module: PermissionModule,
- pub description: &'static str,
- pub permissions: Vec<PermissionInfo>,
-}
-
+// TODO: To be deprecated
#[derive(Debug, serde::Serialize)]
pub struct GroupInfo {
pub group: PermissionGroup,
@@ -122,16 +97,6 @@ pub enum UserStatus {
InvitationSent,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct MerchantSelectRequest {
- pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct AcceptInvitationRequest {
- pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index be467421e65..885ec455e4c 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,8 +1,6 @@
pub use common_enums::PermissionGroup;
use common_enums::{EntityType, RoleScope};
-use super::Permission;
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
pub role_name: String,
@@ -16,17 +14,6 @@ pub struct UpdateRoleRequest {
pub role_name: Option<String>,
}
-#[derive(Debug, serde::Serialize)]
-pub struct ListRolesResponse(pub Vec<RoleInfoWithGroupsResponse>);
-
-#[derive(Debug, serde::Serialize)]
-pub struct RoleInfoWithPermissionsResponse {
- pub role_id: String,
- pub permissions: Vec<Permission>,
- pub role_name: String,
- pub role_scope: RoleScope,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithGroupsResponse {
pub role_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f36ecc18116..9f865c1071e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1135,121 +1135,6 @@ pub async fn create_internal_user(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn switch_merchant_id(
- state: SessionState,
- request: user_api::SwitchMerchantRequest,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- if user_from_token.merchant_id == request.merchant_id {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "User switching to same merchant_id".to_string(),
- )
- .into());
- }
-
- let user = user_from_token.get_user_from_db(&state).await?;
- let key_manager_state = &(&state).into();
- let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_from_token.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .to_not_found_response(UserErrors::InternalServerError)?;
-
- let (token, role_id) = if role_info.is_internal() {
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::MerchantIdNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
-
- let org_id = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &key_store,
- )
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::MerchantIdNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?
- .organization_id;
-
- let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile(
- &state,
- user_from_token.user_id,
- request.merchant_id.clone(),
- org_id.clone(),
- user_from_token.role_id.clone(),
- )
- .await?;
-
- (token, user_from_token.role_id)
- } else {
- let user_roles = state
- .store
- .list_user_roles_by_user_id_and_version(&user_from_token.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let active_user_roles = user_roles
- .into_iter()
- .filter(|role| role.status == UserStatus::Active)
- .collect::<Vec<_>>();
-
- let user_role = active_user_roles
- .iter()
- .find_map(|role| {
- let Some(ref merchant_id) = role.merchant_id else {
- return Some(Err(report!(UserErrors::InternalServerError)));
- };
- if merchant_id == &request.merchant_id {
- Some(Ok(role))
- } else {
- None
- }
- })
- .transpose()?
- .ok_or(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User doesn't have access to switch")?;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user, user_role).await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await;
-
- (token, user_role.role_id.clone())
- };
-
- let response = user_api::DashboardEntryResponse {
- token: token.clone(),
- name: user.get_name(),
- email: user.get_email(),
- user_id: user.get_user_id().to_string(),
- verification_days_left: None,
- user_role: role_id,
- merchant_id: request.merchant_id,
- };
-
- auth::cookies::set_cookie_response(response, token)
-}
-
pub async fn create_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -1282,142 +1167,6 @@ pub async fn create_merchant_account(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn list_merchants_for_user(
- state: SessionState,
- user_from_token: auth::UserIdFromAuth,
-) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
- let user_roles = state
- .store
- .list_user_roles_by_user_id_and_version(
- user_from_token.user_id.as_str(),
- UserRoleVersion::V1,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let merchant_accounts_map = state
- .store
- .list_multiple_merchant_accounts(
- &(&state).into(),
- user_roles
- .iter()
- .map(|role| {
- role.merchant_id
- .clone()
- .ok_or(UserErrors::InternalServerError)
- })
- .collect::<Result<Vec<_>, _>>()?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
- .collect::<HashMap<_, _>>();
-
- let roles_map = futures::future::try_join_all(user_roles.iter().map(|user_role| async {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_role.role_id,
- merchant_id,
- org_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Unable to find role info for user role")
- }))
- .await?
- .into_iter()
- .map(|role_info| (role_info.get_role_id().to_owned(), role_info))
- .collect::<HashMap<_, _>>();
-
- Ok(ApplicationResponse::Json(
- user_roles
- .into_iter()
- .map(|user_role| {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let merchant_account = merchant_accounts_map
- .get(merchant_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Merchant account for user role doesn't exist")?;
-
- let role_info = roles_map
- .get(&user_role.role_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Role info for user role doesn't exist")?;
-
- Ok(user_api::UserMerchantAccount {
- merchant_id: merchant_id.to_owned(),
- merchant_name: merchant_account.merchant_name.clone(),
- is_active: user_role.status == UserStatus::Active,
- role_id: user_role.role_id,
- role_name: role_info.get_role_name().to_string(),
- org_id: org_id.to_owned(),
- })
- })
- .collect::<Result<Vec<_>, _>>()?,
- ))
-}
-
-pub async fn get_user_details_in_merchant_account(
- state: SessionState,
- user_from_token: auth::UserFromToken,
- request: user_api::GetUserRoleDetailsRequest,
- _req_state: ReqState,
-) -> UserResponse<user_api::GetUserRoleDetailsResponse> {
- let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?)
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)?;
-
- let required_user_role = state
- .store
- .find_user_role_by_user_id_merchant_id(
- required_user.get_user_id(),
- &user_from_token.merchant_id,
- UserRoleVersion::V1,
- )
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)
- .attach_printable("User not found in the merchant account")?;
-
- let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &required_user_role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("User role exists but the corresponding role doesn't")?;
-
- Ok(ApplicationResponse::Json(
- user_api::GetUserRoleDetailsResponse {
- email: required_user.get_email(),
- name: required_user.get_name(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- status: required_user_role.status.foreign_into(),
- last_modified_at: required_user_role.last_modified,
- groups: role_info.get_permission_groups().to_vec(),
- role_scope: role_info.get_scope(),
- },
- ))
-}
-
pub async fn list_user_roles_details(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -1670,80 +1419,6 @@ pub async fn list_user_roles_details(
Ok(ApplicationResponse::Json(role_details_list))
}
-pub async fn list_users_for_merchant_account(
- state: SessionState,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::ListUsersResponse> {
- let user_roles: HashMap<String, _> = state
- .store
- .list_user_roles_by_merchant_id(&user_from_token.merchant_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("No user roles for given merchant_id")?
- .into_iter()
- .map(|role| (role.user_id.clone(), role))
- .collect();
-
- let user_ids = user_roles.keys().cloned().collect::<Vec<_>>();
-
- let users = state
- .global_store
- .find_users_by_user_ids(user_ids)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("No users for given merchant_id")?;
-
- let users_and_user_roles: Vec<_> = users
- .into_iter()
- .filter_map(|user| {
- user_roles
- .get(&user.user_id)
- .map(|role| (user.clone(), role.clone()))
- })
- .collect();
-
- let users_user_roles_and_roles =
- futures::future::try_join_all(users_and_user_roles.into_iter().map(
- |(user, user_role)| async {
- roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_role.role_id.clone(),
- user_role
- .merchant_id
- .as_ref()
- .ok_or(UserErrors::InternalServerError)?,
- user_role
- .org_id
- .as_ref()
- .ok_or(UserErrors::InternalServerError)?,
- )
- .await
- .map(|role_info| (user, user_role, role_info))
- .to_not_found_response(UserErrors::InternalServerError)
- },
- ))
- .await?;
-
- let user_details_vec = users_user_roles_and_roles
- .into_iter()
- .map(|(user, user_role, role_info)| {
- let user = domain::UserFromStorage::from(user);
- user_api::UserDetails {
- email: user.get_email(),
- name: user.get_name(),
- role_id: user_role.role_id.clone(),
- role_name: role_info.get_role_name().to_string(),
- status: user_role.status.foreign_into(),
- last_modified_at: user_role.last_modified,
- }
- })
- .collect();
-
- Ok(ApplicationResponse::Json(user_api::ListUsersResponse(
- user_details_vec,
- )))
-}
-
#[cfg(feature = "email")]
pub async fn verify_email_token_only_flow(
state: SessionState,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b841f88eca1..ad37176358b 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -26,6 +26,7 @@ pub mod role;
use common_enums::{EntityType, PermissionGroup};
use strum::IntoEnumIterator;
+// TODO: To be deprecated
pub async fn get_authorization_info_with_groups(
_state: SessionState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
@@ -38,6 +39,7 @@ pub async fn get_authorization_info_with_groups(
),
))
}
+
pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
@@ -253,49 +255,6 @@ pub async fn update_user_role(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn accept_invitation(
- state: SessionState,
- user_token: auth::UserFromToken,
- req: user_role_api::AcceptInvitationRequest,
-) -> UserResponse<()> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.is_empty() || update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- Ok(ApplicationResponse::StatusOk)
-}
-
pub async fn accept_invitations_v2(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -348,67 +307,6 @@ pub async fn accept_invitations_v2(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn merchant_select_token_only_flow(
- state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
- req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenResponse> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.is_empty() || update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_id(user_token.user_id.as_str())
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let current_flow =
- domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
- let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
-
- let token = next_flow.get_token(&state).await?;
-
- let response = user_api::TokenResponse {
- token: token.clone(),
- token_type: next_flow.get_flow().into(),
- };
- auth::cookies::set_cookie_response(response, token)
-}
-
pub async fn accept_invitations_pre_auth(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
@@ -644,20 +542,23 @@ pub async fn delete_user_role(
}
// Check if user has any more role associations
- let user_roles_v2 = state
+ let remaining_roles = state
.store
- .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V2)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user_roles_v1 = state
- .store
- .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V1)
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_db.get_user_id(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: None,
+ limit: None,
+ })
.await
.change_context(UserErrors::InternalServerError)?;
// If user has no more role associated with him then deleting user
- if user_roles_v2.is_empty() && user_roles_v1.is_empty() {
+ if remaining_roles.is_empty() {
state
.global_store
.delete_user_by_user_id(user_from_db.get_user_id())
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index d5d655b4a89..b5b5cab421f 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -83,45 +83,6 @@ pub async fn create_role(
))
}
-pub async fn list_invitable_roles_with_groups(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::ListRolesResponse> {
- let predefined_roles_map = PREDEFINED_ROLES
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .map(
- |(role_id, role_info)| role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- );
-
- let custom_roles_map = state
- .store
- .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|role| {
- let role_info = roles::RoleInfo::from(role);
- role_info
- .is_invitable()
- .then_some(role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- })
- });
-
- Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
- predefined_roles_map.chain(custom_roles_map).collect(),
- )))
-}
-
pub async fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index d14de8c2330..f6cbdd5bbc6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3037,37 +3037,6 @@ impl UserRoleInterface for KafkaStore {
self.diesel_store.insert_user_role(user_role).await
}
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
- self.diesel_store
- .find_user_role_by_user_id(user_id, version)
- .await
- }
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
- self.diesel_store
- .find_user_role_by_user_id_merchant_id(user_id, merchant_id, version)
- .await
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_user_id_and_version(user_id, version)
- .await
- }
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
@@ -3127,16 +3096,6 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_merchant_id(merchant_id, version)
- .await
- }
-
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d511010e6b5..9a5c7149b68 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -54,31 +54,6 @@ pub trait UserRoleInterface {
user_role: InsertUserRolePayload,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
-
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
@@ -132,59 +107,6 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- #[instrument(skip_all)]
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::find_by_user_id(&conn, user_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::find_by_user_id_merchant_id(
- &conn,
- user_id.to_owned(),
- merchant_id.to_owned(),
- version,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::list_by_user_id(&conn, user_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
#[instrument(skip_all)]
async fn find_user_role_by_user_id_and_lineage(
&self,
@@ -335,96 +257,6 @@ impl UserRoleInterface for MockDb {
.collect::<Result<Vec<_>, _>>()
}
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
- user_roles
- .iter()
- .find(|user_role| user_role.user_id == user_id && user_role.version == version)
- .cloned()
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id}"
- ))
- .into(),
- )
- }
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- for user_role in user_roles.iter() {
- let Some(user_role_merchant_id) = &user_role.merchant_id else {
- continue;
- };
- if user_role.user_id == user_id
- && user_role_merchant_id == merchant_id
- && user_role.version == version
- {
- return Ok(user_role.clone());
- }
- }
-
- Err(errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {} and merchant_id = {}",
- user_id,
- merchant_id.get_string_repr()
- ))
- .into())
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- Ok(user_roles
- .iter()
- .cloned()
- .filter_map(|ele| {
- if ele.user_id == user_id && ele.version == version {
- return Some(ele);
- }
- None
- })
- .collect())
- }
-
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- let filtered_roles: Vec<_> = user_roles
- .iter()
- .filter_map(|role| {
- if let Some(role_merchant_id) = &role.merchant_id {
- if role_merchant_id == merchant_id && role.version == version {
- Some(role.clone())
- } else {
- None
- }
- } else {
- None
- }
- })
- .collect();
-
- Ok(filtered_roles)
- }
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index d5f73921a9d..f7ea8cf3649 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1791,26 +1791,11 @@ impl User {
.service(
web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)),
)
- .service(
- web::resource("/switch_merchant").route(web::post().to(user::switch_merchant_id)),
- )
.service(
web::resource("/create_merchant")
.route(web::post().to(user::user_merchant_account_create)),
)
- // TODO: Remove this endpoint once migration to /merchants/list is done
- .service(
- web::resource("/switch/list").route(web::get().to(user::list_merchants_for_user)),
- )
- .service(
- web::resource("/merchants/list")
- .route(web::get().to(user::list_merchants_for_user)),
- )
- // The route is utilized to select an invitation from a list of merchants in an intermediate state
- .service(
- web::resource("/merchants_select/list")
- .route(web::get().to(user::list_merchants_for_user)),
- )
+ // TODO: To be deprecated
.service(
web::resource("/permission_info")
.route(web::get().to(user_role::get_authorization_info)),
@@ -1952,12 +1937,13 @@ impl User {
// User management
route = route.service(
web::scope("/user")
- .service(web::resource("").route(web::get().to(user::get_user_role_details)))
+ .service(web::resource("").route(web::post().to(user::list_user_roles_details)))
+ // TODO: To be deprecated
.service(web::resource("/v2").route(web::post().to(user::list_user_roles_details)))
.service(
- web::resource("/list")
- .route(web::get().to(user::list_users_for_merchant_account)),
+ web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)),
)
+ // TODO: To be deprecated
.service(
web::resource("/v2/list")
.route(web::get().to(user_role::list_users_in_lineage)),
@@ -1970,8 +1956,11 @@ impl User {
web::scope("/invite/accept")
.service(
web::resource("")
- .route(web::post().to(user_role::merchant_select))
- .route(web::put().to(user_role::accept_invitation)),
+ .route(web::post().to(user_role::accept_invitations_v2)),
+ )
+ .service(
+ web::resource("/pre_auth")
+ .route(web::post().to(user_role::accept_invitations_pre_auth)),
)
.service(
web::scope("/v2")
@@ -1996,36 +1985,38 @@ impl User {
);
// Role information
- route = route.service(
- web::scope("/role")
- .service(
- web::resource("")
- .route(web::get().to(user_role::get_role_from_token))
- .route(web::post().to(user_role::create_role)),
- )
- .service(
- web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)),
- )
- .service(
- web::scope("/list")
- .service(web::resource("").route(web::get().to(user_role::list_all_roles)))
- .service(
- web::resource("/invite").route(
+ route =
+ route.service(
+ web::scope("/role")
+ .service(
+ web::resource("")
+ .route(web::get().to(user_role::get_role_from_token))
+ .route(web::post().to(user_role::create_role)),
+ )
+ // TODO: To be deprecated
+ .service(
+ web::resource("/v2/list")
+ .route(web::get().to(user_role::list_roles_with_info)),
+ )
+ .service(
+ web::scope("/list")
+ .service(
+ web::resource("")
+ .route(web::get().to(user_role::list_roles_with_info)),
+ )
+ .service(web::resource("/invite").route(
web::get().to(user_role::list_invitable_roles_at_entity_level),
- ),
- )
- .service(
- web::resource("/update").route(
+ ))
+ .service(web::resource("/update").route(
web::get().to(user_role::list_updatable_roles_at_entity_level),
- ),
- ),
- )
- .service(
- web::resource("/{role_id}")
- .route(web::get().to(user_role::get_role))
- .route(web::put().to(user_role::update_role)),
- ),
- );
+ )),
+ )
+ .service(
+ web::resource("/{role_id}")
+ .route(web::get().to(user_role::get_role))
+ .route(web::put().to(user_role::update_role)),
+ ),
+ );
#[cfg(feature = "dummy_connector")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 482bc40c49f..18211b7fbb0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -219,16 +219,13 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
| Flow::SwitchOrg
- | Flow::SwitchMerchant
| Flow::SwitchMerchantV2
| Flow::SwitchProfile
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
- | Flow::UserMerchantAccountList
| Flow::GetUserDetails
| Flow::GetUserRoleDetails
- | Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::RotatePassword
@@ -259,8 +256,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListInvitationsForUser
| Flow::AuthSelect => Self::User,
- Flow::ListRoles
- | Flow::ListRolesV2
+ Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
@@ -268,9 +264,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
- | Flow::AcceptInvitation
| Flow::AcceptInvitationsV2
- | Flow::MerchantSelect
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index b1fbd2bb6df..4ed2280c6a3 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -228,24 +228,6 @@ pub async fn internal_user_signup(
.await
}
-pub async fn switch_merchant_id(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- json_payload: web::Json<user_api::SwitchMerchantRequest>,
-) -> HttpResponse {
- let flow = Flow::SwitchMerchant;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &http_req,
- json_payload.into_inner(),
- |state, user, req, _| user_core::switch_merchant_id(state, req, user),
- &auth::DashboardNoPermissionAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn user_merchant_account_create(
state: web::Data<AppState>,
req: HttpRequest,
@@ -316,41 +298,6 @@ pub async fn delete_sample_data(
.await
}
-pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::UserMerchantAccountList;
- Box::pin(api::server_wrap(
- flow,
- state,
- &req,
- (),
- |state, user, _, _| user_core::list_merchants_for_user(state, user),
- &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
-pub async fn get_user_role_details(
- state: web::Data<AppState>,
- req: HttpRequest,
- payload: web::Query<user_api::GetUserRoleDetailsRequest>,
-) -> HttpResponse {
- let flow = Flow::GetUserDetails;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- user_core::get_user_details_in_merchant_account,
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn list_user_roles_details(
state: web::Data<AppState>,
req: HttpRequest,
@@ -372,26 +319,6 @@ pub async fn list_user_roles_details(
.await
}
-pub async fn list_users_for_merchant_account(
- state: web::Data<AppState>,
- req: HttpRequest,
-) -> HttpResponse {
- let flow = Flow::ListUsersForMerchantAccount;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- (),
- |state, user, _, _| user_core::list_users_for_merchant_account(state, user),
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn rotate_password(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 922e7612b14..777cbe1fd95 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -16,6 +16,7 @@ use crate::{
},
};
+// TODO: To be deprecated
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
@@ -76,25 +77,6 @@ pub async fn create_role(
.await
}
-pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::ListRoles;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- (),
- |state, user, _, _| async move {
- role_core::list_invitable_roles_with_groups(state, user).await
- },
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
@@ -167,25 +149,6 @@ pub async fn update_user_role(
.await
}
-pub async fn accept_invitation(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<user_role_api::AcceptInvitationRequest>,
-) -> HttpResponse {
- let flow = Flow::AcceptInvitation;
- let payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, user, req_body, _| user_role_core::accept_invitation(state, user, req_body),
- &auth::DashboardNoPermissionAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn accept_invitations_v2(
state: web::Data<AppState>,
req: HttpRequest,
@@ -205,27 +168,6 @@ pub async fn accept_invitations_v2(
.await
}
-pub async fn merchant_select(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<user_role_api::MerchantSelectRequest>,
-) -> HttpResponse {
- let flow = Flow::MerchantSelect;
- let payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, user, req_body, _| async move {
- user_role_core::merchant_select_token_only_flow(state, user, req_body).await
- },
- &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn accept_invitations_pre_auth(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 822035c7925..7cfde3efeea 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,21 +1,17 @@
use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo};
use common_enums::PermissionGroup;
-use strum::{EnumIter, IntoEnumIterator};
+use strum::IntoEnumIterator;
use super::{permission_groups::get_permissions_vec, permissions::Permission};
-pub fn get_module_authorization_info() -> Vec<ModuleInfo> {
- PermissionModule::iter()
- .map(|module| ModuleInfo::new(&module))
- .collect()
-}
-
+// TODO: To be deprecated
pub fn get_group_authorization_info() -> Vec<GroupInfo> {
PermissionGroup::iter()
.map(get_group_info_from_permission_group)
.collect()
}
+// TODO: To be deprecated
pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> {
permissions
.iter()
@@ -26,169 +22,7 @@ pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<P
.collect()
}
-// TODO: Deprecate once groups are stable
-#[derive(PartialEq, EnumIter, Clone)]
-pub enum PermissionModule {
- Payments,
- Refunds,
- MerchantAccount,
- Connectors,
- Routing,
- Analytics,
- Mandates,
- Customer,
- Disputes,
- ThreeDsDecisionManager,
- SurchargeDecisionManager,
- AccountCreate,
- Payouts,
- Recon,
-}
-
-impl PermissionModule {
- pub fn get_module_description(&self) -> &'static str {
- match self {
- Self::Payments => "Everything related to payments - like creating and viewing payment related information are within this module",
- Self::Refunds => "Refunds module encompasses everything related to refunds - like creating and viewing payment related information",
- Self::MerchantAccount => "Accounts module permissions allow the user to view and update account details, configure webhooks and much more",
- Self::Connectors => "All connector related actions - like configuring new connectors, viewing and updating connector configuration lies with this module",
- Self::Routing => "All actions related to new, active, and past routing stacks take place here",
- Self::Analytics => "Permission to view and analyse the data relating to payments, refunds, sdk etc.",
- Self::Mandates => "Everything related to mandates - like creating and viewing mandate related information are within this module",
- Self::Customer => "Everything related to customers - like creating and viewing customer related information are within this module",
- Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module",
- Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant",
- Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant",
- Self::AccountCreate => "Create new account within your organization",
- Self::Payouts => "Everything related to payouts - like creating and viewing payout related information are within this module",
- Self::Recon => "Everything related to recon - raise requests for activating recon and generate recon auth tokens",
- }
- }
-}
-
-// TODO: Deprecate once groups are stable
-pub struct ModuleInfo {
- pub module: PermissionModule,
- pub description: &'static str,
- pub permissions: Vec<PermissionInfo>,
-}
-
-impl ModuleInfo {
- pub fn new(module: &PermissionModule) -> Self {
- let module_name = module.clone();
- let description = module.get_module_description();
-
- match module {
- PermissionModule::Payments => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::PaymentRead,
- Permission::PaymentWrite,
- ]),
- },
- PermissionModule::Refunds => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::RefundRead,
- Permission::RefundWrite,
- ]),
- },
- PermissionModule::MerchantAccount => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- ]),
- },
- PermissionModule::Connectors => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- ]),
- },
- PermissionModule::Routing => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::RoutingRead,
- Permission::RoutingWrite,
- ]),
- },
- PermissionModule::Analytics => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[Permission::Analytics]),
- },
- PermissionModule::Mandates => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MandateRead,
- Permission::MandateWrite,
- ]),
- },
- PermissionModule::Customer => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::CustomerRead,
- Permission::CustomerWrite,
- ]),
- },
- PermissionModule::Disputes => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::DisputeRead,
- Permission::DisputeWrite,
- ]),
- },
- PermissionModule::ThreeDsDecisionManager => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::ThreeDsDecisionManagerRead,
- Permission::ThreeDsDecisionManagerWrite,
- ]),
- },
-
- PermissionModule::SurchargeDecisionManager => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::SurchargeDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- ]),
- },
- PermissionModule::AccountCreate => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantAccountCreate,
- ]),
- },
- PermissionModule::Payouts => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ]),
- },
- PermissionModule::Recon => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[Permission::ReconAdmin]),
- },
- }
- }
-}
-
+// TODO: To be deprecated
fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
let description = get_group_description(group);
GroupInfo {
@@ -198,6 +32,7 @@ fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
}
}
+// TODO: To be deprecated
fn get_group_description(group: PermissionGroup) -> &'static str {
match group {
PermissionGroup::OperationsView => {
@@ -250,10 +85,10 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
ParentGroup::Connectors => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
- ParentGroup::Analytics => "View Analytics",
+ ParentGroup::Analytics => "View Analytics",
ParentGroup::Users => "Manage and invite Users to the Team",
- ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
- ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
- ParentGroup::Recon => "View and manage reconciliation reports",
+ ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
+ ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
+ ParentGroup::Recon => "View and manage reconciliation reports",
}
}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 19d682aeef1..6361b82afb4 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -32,7 +32,7 @@ use crate::{
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
- services::{self, authentication::UserFromToken, authorization::info},
+ services::{self, authentication::UserFromToken},
types::transformers::ForeignFrom,
utils::user::password,
};
@@ -1019,37 +1019,6 @@ impl UserFromStorage {
}
}
-impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
- fn from(value: info::ModuleInfo) -> Self {
- Self {
- module: value.module.into(),
- description: value.description,
- permissions: value.permissions.into_iter().map(Into::into).collect(),
- }
- }
-}
-
-impl From<info::PermissionModule> for user_role_api::PermissionModule {
- fn from(value: info::PermissionModule) -> Self {
- match value {
- info::PermissionModule::Payments => Self::Payments,
- info::PermissionModule::Refunds => Self::Refunds,
- info::PermissionModule::MerchantAccount => Self::MerchantAccount,
- info::PermissionModule::Connectors => Self::Connectors,
- info::PermissionModule::Routing => Self::Routing,
- info::PermissionModule::Analytics => Self::Analytics,
- info::PermissionModule::Mandates => Self::Mandates,
- info::PermissionModule::Customer => Self::Customer,
- info::PermissionModule::Disputes => Self::Disputes,
- info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager,
- info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager,
- info::PermissionModule::AccountCreate => Self::AccountCreate,
- info::PermissionModule::Payouts => Self::Payouts,
- info::PermissionModule::Recon => Self::Recon,
- }
- }
-}
-
impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
fn foreign_from(value: UserStatus) -> Self {
match value {
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 22edf6768c8..8975519fd97 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -5,8 +5,7 @@ use common_enums::UserAuthType;
use common_utils::{
encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier,
};
-use diesel_models::user_role::UserRole;
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionPool;
@@ -86,45 +85,6 @@ impl UserFromToken {
}
}
-pub async fn generate_jwt_auth_token_without_profile(
- state: &SessionState,
- user: &UserFromStorage,
- user_role: &UserRole,
-) -> UserResult<Secret<String>> {
- let token = AuthToken::new_token(
- user.get_user_id().to_string(),
- user_role
- .merchant_id
- .as_ref()
- .ok_or(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role")?
- .clone(),
- user_role.role_id.clone(),
- &state.conf,
- user_role
- .org_id
- .as_ref()
- .ok_or(report!(UserErrors::InternalServerError))
- .attach_printable("org_id not found for user_role")?
- .clone(),
- None,
- )
- .await?;
- Ok(Secret::new(token))
-}
-
-pub async fn generate_jwt_auth_token_with_attributes_without_profile(
- state: &SessionState,
- user_id: String,
- merchant_id: id_type::MerchantId,
- org_id: id_type::OrganizationId,
- role_id: String,
-) -> UserResult<Secret<String>> {
- let token =
- AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?;
- Ok(Secret::new(token))
-}
-
pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
user_id: String,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 603c5cc91c1..2bae094fd96 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -364,8 +364,6 @@ pub enum Flow {
InternalUserSignup,
/// Switch org
SwitchOrg,
- /// Switch merchant
- SwitchMerchant,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
@@ -374,8 +372,6 @@ pub enum Flow {
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
- /// List roles
- ListRoles,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
@@ -394,14 +390,10 @@ pub enum Flow {
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
- /// List merchant accounts for user
- UserMerchantAccountList,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
- /// List users for merchant account
- ListUsersForMerchantAccount,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
@@ -434,12 +426,8 @@ pub enum Flow {
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
- /// Accept user invitation using merchant_ids
- AcceptInvitation,
/// Accept user invitation using entities
AcceptInvitationsV2,
- /// Select merchant from invitations
- MerchantSelect,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
| 2024-09-26T12:17:17Z |
## Description
<!-- Describe your changes in detail -->
Deletions
- `/user/switch_merchant`
- `/user/switch/list`
- `/user/merchants/list`
- `/user/merchant_select/list`
Modifications
- `/user/user` will work same as `/user/user/v2`
- `/user/user/list` will work same as `/user/user/v2/list`
- `/user/user/invite/accept` will work same as `/user/user/invite/accept/v2`
- `/user/user/invite/accept/pre_auth` will work same as `/user/user/invite/accept/v2/pre_auth`
- `/user/role/list` will work same as `/user/role/v2/list`
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes [#6112](https://github.com/juspay/hyperswitch/issues/6112).
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the below APIs with throw 404.
- `/user/switch_merchant`
- `/user/switch/list`
- `/user/merchants/list`
- `/user/merchant_select/list`
All the below APIs with behave differently.
- `/user/user` will work same as `/user/user/v2`
- `/user/user/list` will work same as `/user/user/v2/list`
- `/user/user/invite/accept` will work same as `/user/user/invite/accept/v2`
- `/user/user/invite/accept/pre_auth` will work same as `/user/user/invite/accept/v2/pre_auth`
- `/user/role/list` will work same as `/user/role/v2/list` | 67d6d2247bb53dc25831d65305269ba6889c99de |
All the below APIs with throw 404.
- `/user/switch_merchant`
- `/user/switch/list`
- `/user/merchants/list`
- `/user/merchant_select/list`
All the below APIs with behave differently.
- `/user/user` will work same as `/user/user/v2`
- `/user/user/list` will work same as `/user/user/v2/list`
- `/user/user/invite/accept` will work same as `/user/user/invite/accept/v2`
- `/user/user/invite/accept/pre_auth` will work same as `/user/user/invite/accept/v2/pre_auth`
- `/user/role/list` will work same as `/user/role/v2/list`
| [
"crates/api_models/src/events/user.rs",
"crates/api_models/src/events/user_role.rs",
"crates/api_models/src/user.rs",
"crates/api_models/src/user_role.rs",
"crates/api_models/src/user_role/role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_r... | |
juspay/hyperswitch | juspay__hyperswitch-6115 | Bug: fix: env added for hyperswitch-web
Added env for hyperswitch-web | diff --git a/docker-compose.yml b/docker-compose.yml
index ef6ff17b5e9..f766ff91053 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -162,6 +162,7 @@ services:
- SELF_SERVER_URL=http://localhost:5252
- SDK_ENV=local
- ENV_LOGGING_URL=http://localhost:3103
+ - ENV_BACKEND_URL=http://localhost:8080
labels:
logs: "promtail"
| 2024-09-26T12:12:55Z |
## Description
In docker for hyperswitch-web we were facing that it's always pointing to beta.hyperswitch.io as `ENV_BACKEND_URL` was not getting passed.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
Via checking HyperLoader.js file at 9050 port. | 8049993320e0c103d72dcae0497928ba622d7b59 | Via checking HyperLoader.js file at 9050 port.
| [
"docker-compose.yml"
] | |
juspay/hyperswitch | juspay__hyperswitch-5940 | Bug: [REFACTOR] Move Hardcoded Email Subjects to Constants Across the User Related Files
### Feature Description
In the current implementation, email subjects are hardcoded at multiple places across the codebase when constructing email content. To improve maintainability and avoid magic strings, each unique subject should be moved to its own constant. The goal of this issue is to identify all the places where email subjects are hardcoded, create a corresponding constant for each one, and replace the hardcoded values with the newly defined constants.
### Possible Implementation
- Search the codebase for all instances where email subjects are hardcoded.
Example: https://github.com/juspay/hyperswitch/blob/b2364414edab6d44e276f2133bc988610693f155/crates/router/src/core/user.rs#L707
- For each unique subject, create a new constant in `crates/router/src/consts/user.rs`.
- Refactor the code by replacing the hardcoded subjects with their respective constants.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. | diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 9e70cb2b96b..728933a4614 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -86,6 +86,11 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_";
+pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice";
+pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by";
+pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str =
+ "Approval of Recon Request - Access Granted to Recon Dashboard";
+
pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_";
#[cfg(feature = "olap")]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 6ac2b08e6bb..5984a876503 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -26,3 +26,10 @@ pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes
pub const REDIS_SSO_PREFIX: &str = "SSO_";
pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes
+
+/// Email subject
+pub const EMAIL_SUBJECT_SIGNUP: &str = "Welcome to the Hyperswitch community!";
+pub const EMAIL_SUBJECT_INVITATION: &str = "You have been invited to join Hyperswitch Community!";
+pub const EMAIL_SUBJECT_MAGIC_LINK: &str = "Unlock Hyperswitch: Use Your Magic Link to Sign In";
+pub const EMAIL_SUBJECT_RESET_PASSWORD: &str = "Get back to Hyperswitch - Reset Your Password Now";
+pub const EMAIL_SUBJECT_NEW_PROD_INTENT: &str = "New Prod Intent";
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs
index d5f824e0cce..ea3459709c6 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -39,7 +39,8 @@ pub async fn send_recon_request(
.attach_printable("Failed to convert recipient's email to UserEmail")?,
settings: state.conf.clone(),
subject: format!(
- "Dashboard Pro Feature Request by {}",
+ "{} {}",
+ consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,
user_email.expose().peek()
),
};
@@ -145,7 +146,7 @@ pub async fn recon_merchant_account_update(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form username")?,
settings: state.conf.clone(),
- subject: "Approval of Recon Request - Access Granted to Recon Dashboard",
+ subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,
};
if req.recon_status == enums::ReconStatus::Active {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f36ecc18116..d5a9c143bea 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -75,7 +75,7 @@ pub async fn signup_with_merchant_id(
recipient_email: user_from_db.get_email().try_into()?,
user_name: domain::UserName::new(user_from_db.get_name())?,
settings: state.conf.clone(),
- subject: "Get back to Hyperswitch - Reset Your Password Now",
+ subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD,
auth_id,
};
@@ -204,7 +204,7 @@ pub async fn connect_account(
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
- subject: "Unlock Hyperswitch: Use Your Magic Link to Sign In",
+ subject: consts::user::EMAIL_SUBJECT_MAGIC_LINK,
auth_id,
};
@@ -254,7 +254,7 @@ pub async fn connect_account(
let email_contents = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
- subject: "Welcome to the Hyperswitch community!",
+ subject: consts::user::EMAIL_SUBJECT_SIGNUP,
auth_id,
};
@@ -374,7 +374,7 @@ pub async fn forgot_password(
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
- subject: "Get back to Hyperswitch - Reset Your Password Now",
+ subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD,
auth_id,
};
@@ -702,7 +702,7 @@ async fn handle_existing_user_invitation(
recipient_email: invitee_email,
user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
+ subject: consts::user::EMAIL_SUBJECT_INVITATION,
entity,
auth_id: auth_id.clone(),
};
@@ -823,7 +823,7 @@ async fn handle_new_user_invitation(
recipient_email: invitee_email,
user_name: domain::UserName::new(new_user.get_name())?,
settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
+ subject: consts::user::EMAIL_SUBJECT_INVITATION,
entity,
auth_id: auth_id.clone(),
};
@@ -942,7 +942,7 @@ pub async fn resend_invite(
recipient_email: invitee_email,
user_name: domain::UserName::new(user.get_name())?,
settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
+ subject: consts::user::EMAIL_SUBJECT_INVITATION,
entity: email_types::Entity {
entity_id,
entity_type,
@@ -1823,7 +1823,7 @@ pub async fn send_verification_mail(
let email_contents = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user.email)?,
settings: state.conf.clone(),
- subject: "Welcome to the Hyperswitch community!",
+ subject: consts::user::EMAIL_SUBJECT_SIGNUP,
auth_id,
};
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 1c4ce79ac8c..cedd17828f1 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -417,7 +417,7 @@ impl BizEmailProd {
state.conf.email.prod_intent_recipient_email.clone(),
)?,
settings: state.conf.clone(),
- subject: "New Prod Intent",
+ subject: consts::user::EMAIL_SUBJECT_NEW_PROD_INTENT,
user_name: data.poc_name.unwrap_or_default().into(),
poc_email: data.poc_email.unwrap_or_default().into(),
legal_business_name: data.legal_business_name.unwrap_or_default(),
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index b26e9862e81..c04e4c5d576 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -6,7 +6,7 @@ use router_env::{logger, metrics::add_attributes};
use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState};
use crate::{
- errors,
+ consts, errors,
logger::error,
routes::{metrics, SessionState},
services::email::types::ApiKeyExpiryReminder,
@@ -81,7 +81,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
);
errors::ProcessTrackerError::EApiErrorResponse
})?,
- subject: "API Key Expiry Notice",
+ subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY,
expires_in: *expires_in,
api_key_name,
prefix,
| 2024-09-26T11:47:50Z |
## Description
Change the hardcoded email subject to constants
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## Motivation and Context
refactor based on this issue - #5940
[link](https://github.com/juspay/hyperswitch/issues/5940)
Closes #5940.
## How did you test it?
This is an internal change for email subjects.
There should be no affect. All email subjects like magic link, invite should be properly sent as before.
[change_apply_before.txt](https://github.com/user-attachments/files/17147768/change_apply_before.txt)
[change_apply_after.txt](https://github.com/user-attachments/files/17147771/change_apply_after.txt) | 05080259132fb12cdef40a999bd02b6fe2beeeaa | This is an internal change for email subjects.
There should be no affect. All email subjects like magic link, invite should be properly sent as before.
[change_apply_before.txt](https://github.com/user-attachments/files/17147768/change_apply_before.txt)
[change_apply_after.txt](https://github.com/user-attachments/files/17147771/change_apply_after.txt)
| [
"crates/router/src/consts.rs",
"crates/router/src/consts/user.rs",
"crates/router/src/core/recon.rs",
"crates/router/src/core/user.rs",
"crates/router/src/services/email/types.rs",
"crates/router/src/workflows/api_key_expiry.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6116 | Bug: [FEATURE] Update worldpay connector's integration
# Storing long connector transaction IDs (\>128 characters)
## Aim
This issue describes the approach for efficiently storing long connector transaction IDs in HyperSwitch application.
## Context
HyperSwitch is integrated with multiple connectors, these underlying connectors generate their own resource IDs which are stored in HyperSwitch DB for future references and / or debugging.
For payments, this is stored in payment\_attempt table \- `connector_transaction_id`
For refunds, this is stored in refunds table \- `connector_refund_id`
For captures, this is stored in captures table \- `connector_capture_id`
Both these columns are of size 128 characters in length, giving ample amount of space for storing these resource identifiers.
Some connectors \- like Worldpay, use a different approach for their resource identifiers. Worldpay uses an encrypted token as its resource identifier whose length usually exceeds 450 characters.
HyperSwitch cannot keep increasing the length of these two columns for storing IDs with such large lengths due to performance impacts on both read and write, specifically during webhooks flows as `connector_transaction_id` is an indexed column.
## Solution
Includes a bug fix and basically migrates the API endpoints to consume the v7 endpoints.
Bug fix -`entity` is a param in their API spec for specifying the merchant's account.
The solution requires making changes in two places \-
1. Convert `connector_transaction_id` to a typed enum with two variants in the application
1. `ConnectorTxnId`
2. `HashedConnectorData`
2. Introduce a new column per table for storing such large resource identifiers.
### Pre-requisites
- Add a new column `connector_transaction_data`
### Storing large IDs
- If input string length \> 128 characters, store this data in `connector_transaction_data`
- Create a one-way hash of this data and store it in `connector_transaction_id` with a prefix `hs_hash_`
### Consuming large IDs
- If input string length \> 128 characters, create a hash and query using the hashed value
- Deserialize `connector_transaction_id` into a typed variant \- either `ConnectorTxnId` or `HashedConnectorData` based on the prefix (`hs_hash_`)
- If it’s `HashedConnectorData`, use `connector_transaction_data` as resource ID
## Example
Let’s say we want to extend storage of such IDs to payment attempts table
1. Add a new column in the said table \- `connector_transaction_data`
2. While receiving these IDs (assuming length \>128), store in `connector_transaction_data`
3. Create a one-way hash and store in `connector_transaction_id`
4. While querying using these IDs (webhooks flow), create a hash and query using the hashed value
5. Use `connector_transaction_data` instead of `connector_transaction_id` in application and application responses
## Notes
- Never expose the hashed `connector_transaction_id’s` outside the system, i.e. in API responses or webhook responses
- Deserialize into `HashedConnectorData` only when the `connector_transaction_id` is prefixed with `hs_hash_`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index e16a206b118..5d6d4049dea 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -6018,6 +6018,7 @@
"description": "The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar.",
"enum": [
"AED",
+ "AFN",
"ALL",
"AMD",
"ANG",
@@ -6037,10 +6038,12 @@
"BOB",
"BRL",
"BSD",
+ "BTN",
"BWP",
"BYN",
"BZD",
"CAD",
+ "CDF",
"CHF",
"CLP",
"CNY",
@@ -6054,6 +6057,7 @@
"DOP",
"DZD",
"EGP",
+ "ERN",
"ETB",
"EUR",
"FJD",
@@ -6075,6 +6079,8 @@
"ILS",
"INR",
"IQD",
+ "IRR",
+ "ISK",
"JMD",
"JOD",
"JPY",
@@ -6082,6 +6088,7 @@
"KGS",
"KHR",
"KMF",
+ "KPW",
"KRW",
"KWD",
"KYD",
@@ -6128,6 +6135,7 @@
"SAR",
"SBD",
"SCR",
+ "SDG",
"SEK",
"SGD",
"SHP",
@@ -6138,8 +6146,11 @@
"SSP",
"STN",
"SVC",
+ "SYP",
"SZL",
"THB",
+ "TJS",
+ "TMT",
"TND",
"TOP",
"TRY",
@@ -6161,7 +6172,8 @@
"XPF",
"YER",
"ZAR",
- "ZMW"
+ "ZMW",
+ "ZWL"
]
},
"CustomerAcceptance": {
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 4f742a61698..dafc6048154 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -323,8 +323,10 @@ upi_collect = {country = "IN", currency = "INR"}
open_banking_pis = {currency = "EUR,GBP"}
[pm_filters.worldpay]
-apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
-google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN"
+debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
+apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" }
[pm_filters.zen]
boleto = { country = "BR", currency = "BRL" }
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index c25b70d6ba0..caf8c030568 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -336,8 +336,10 @@ upi_collect = {country = "IN", currency = "INR"}
open_banking_pis = {currency = "EUR,GBP"}
[pm_filters.worldpay]
-apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
-google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN"
+debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
+apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" }
[pm_filters.zen]
boleto = { country = "BR", currency = "BRL" }
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 28f5a4e0575..6cc1193ab55 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -340,6 +340,8 @@ upi_collect = {country = "IN", currency = "INR"}
open_banking_pis = {currency = "EUR,GBP"}
[pm_filters.worldpay]
+debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SAR,RSD,SCR,SLL,SG,ST,SBD,SOS,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,TMT,AED,UG,UA,US,UZ,VU,VE,VN,YER,CNY,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SAR,RSD,SCR,SLL,SG,ST,SBD,SOS,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,TMT,AED,UG,UA,US,UZ,VU,VE,VN,YER,CNY,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN"
diff --git a/config/development.toml b/config/development.toml
index 0153c6ef102..4c2f1cf718e 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -518,6 +518,8 @@ google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" }
paypal = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" }
[pm_filters.worldpay]
+debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 5ffe5df138f..d55e722b3e0 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -441,6 +441,12 @@ credit = { currency = "USD" }
debit = { currency = "USD" }
ach = { currency = "USD" }
+[pm_filters.worldpay]
+debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" }
+google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
+apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" }
+
[bank_config.online_banking_fpx]
adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 0a87e6c19aa..8306deeb258 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -558,6 +558,7 @@ pub enum CallConnectorAction {
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum Currency {
AED,
+ AFN,
ALL,
AMD,
ANG,
@@ -577,10 +578,12 @@ pub enum Currency {
BOB,
BRL,
BSD,
+ BTN,
BWP,
BYN,
BZD,
CAD,
+ CDF,
CHF,
CLP,
CNY,
@@ -594,6 +597,7 @@ pub enum Currency {
DOP,
DZD,
EGP,
+ ERN,
ETB,
EUR,
FJD,
@@ -615,6 +619,8 @@ pub enum Currency {
ILS,
INR,
IQD,
+ IRR,
+ ISK,
JMD,
JOD,
JPY,
@@ -622,6 +628,7 @@ pub enum Currency {
KGS,
KHR,
KMF,
+ KPW,
KRW,
KWD,
KYD,
@@ -668,6 +675,7 @@ pub enum Currency {
SAR,
SBD,
SCR,
+ SDG,
SEK,
SGD,
SHP,
@@ -678,8 +686,11 @@ pub enum Currency {
SSP,
STN,
SVC,
+ SYP,
SZL,
THB,
+ TJS,
+ TMT,
TND,
TOP,
TRY,
@@ -703,6 +714,7 @@ pub enum Currency {
YER,
ZAR,
ZMW,
+ ZWL,
}
impl Currency {
@@ -756,6 +768,7 @@ impl Currency {
pub fn iso_4217(&self) -> &'static str {
match *self {
Self::AED => "784",
+ Self::AFN => "971",
Self::ALL => "008",
Self::AMD => "051",
Self::ANG => "532",
@@ -775,10 +788,12 @@ impl Currency {
Self::BOB => "068",
Self::BRL => "986",
Self::BSD => "044",
+ Self::BTN => "064",
Self::BWP => "072",
Self::BYN => "933",
Self::BZD => "084",
Self::CAD => "124",
+ Self::CDF => "976",
Self::CHF => "756",
Self::CLP => "152",
Self::COP => "170",
@@ -791,6 +806,7 @@ impl Currency {
Self::DOP => "214",
Self::DZD => "012",
Self::EGP => "818",
+ Self::ERN => "232",
Self::ETB => "230",
Self::EUR => "978",
Self::FJD => "242",
@@ -812,6 +828,8 @@ impl Currency {
Self::ILS => "376",
Self::INR => "356",
Self::IQD => "368",
+ Self::IRR => "364",
+ Self::ISK => "352",
Self::JMD => "388",
Self::JOD => "400",
Self::JPY => "392",
@@ -819,6 +837,7 @@ impl Currency {
Self::KGS => "417",
Self::KHR => "116",
Self::KMF => "174",
+ Self::KPW => "408",
Self::KRW => "410",
Self::KWD => "414",
Self::KYD => "136",
@@ -866,6 +885,7 @@ impl Currency {
Self::SAR => "682",
Self::SBD => "090",
Self::SCR => "690",
+ Self::SDG => "938",
Self::SEK => "752",
Self::SGD => "702",
Self::SHP => "654",
@@ -876,8 +896,11 @@ impl Currency {
Self::SSP => "728",
Self::STN => "930",
Self::SVC => "222",
+ Self::SYP => "760",
Self::SZL => "748",
Self::THB => "764",
+ Self::TJS => "972",
+ Self::TMT => "934",
Self::TND => "788",
Self::TOP => "776",
Self::TRY => "949",
@@ -900,6 +923,7 @@ impl Currency {
Self::YER => "886",
Self::ZAR => "710",
Self::ZMW => "967",
+ Self::ZWL => "932",
}
}
@@ -909,6 +933,7 @@ impl Currency {
| Self::CLP
| Self::DJF
| Self::GNF
+ | Self::IRR
| Self::JPY
| Self::KMF
| Self::KRW
@@ -922,6 +947,7 @@ impl Currency {
| Self::XOF
| Self::XPF => true,
Self::AED
+ | Self::AFN
| Self::ALL
| Self::AMD
| Self::ANG
@@ -940,10 +966,12 @@ impl Currency {
| Self::BOB
| Self::BRL
| Self::BSD
+ | Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
+ | Self::CDF
| Self::CHF
| Self::CNY
| Self::COP
@@ -955,6 +983,7 @@ impl Currency {
| Self::DOP
| Self::DZD
| Self::EGP
+ | Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
@@ -975,11 +1004,13 @@ impl Currency {
| Self::ILS
| Self::INR
| Self::IQD
+ | Self::ISK
| Self::JMD
| Self::JOD
| Self::KES
| Self::KGS
| Self::KHR
+ | Self::KPW
| Self::KWD
| Self::KYD
| Self::KZT
@@ -1022,6 +1053,7 @@ impl Currency {
| Self::SAR
| Self::SBD
| Self::SCR
+ | Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
@@ -1032,8 +1064,11 @@ impl Currency {
| Self::SSP
| Self::STN
| Self::SVC
+ | Self::SYP
| Self::SZL
| Self::THB
+ | Self::TJS
+ | Self::TMT
| Self::TND
| Self::TOP
| Self::TRY
@@ -1049,7 +1084,8 @@ impl Currency {
| Self::XCD
| Self::YER
| Self::ZAR
- | Self::ZMW => false,
+ | Self::ZMW
+ | Self::ZWL => false,
}
}
@@ -1059,6 +1095,7 @@ impl Currency {
true
}
Self::AED
+ | Self::AFN
| Self::ALL
| Self::AMD
| Self::AOA
@@ -1077,10 +1114,12 @@ impl Currency {
| Self::BOB
| Self::BRL
| Self::BSD
+ | Self::BTN
| Self::BWP
| Self::BYN
| Self::BZD
| Self::CAD
+ | Self::CDF
| Self::CHF
| Self::CLP
| Self::CNY
@@ -1094,6 +1133,7 @@ impl Currency {
| Self::DOP
| Self::DZD
| Self::EGP
+ | Self::ERN
| Self::ETB
| Self::EUR
| Self::FJD
@@ -1114,12 +1154,15 @@ impl Currency {
| Self::IDR
| Self::ILS
| Self::INR
+ | Self::IRR
+ | Self::ISK
| Self::JMD
| Self::JPY
| Self::KES
| Self::KGS
| Self::KHR
| Self::KMF
+ | Self::KPW
| Self::KRW
| Self::KYD
| Self::KZT
@@ -1163,6 +1206,7 @@ impl Currency {
| Self::SAR
| Self::SBD
| Self::SCR
+ | Self::SDG
| Self::SEK
| Self::SGD
| Self::SHP
@@ -1173,8 +1217,11 @@ impl Currency {
| Self::SSP
| Self::STN
| Self::SVC
+ | Self::SYP
| Self::SZL
| Self::THB
+ | Self::TJS
+ | Self::TMT
| Self::TOP
| Self::TRY
| Self::TTD
@@ -1195,7 +1242,8 @@ impl Currency {
| Self::XOF
| Self::YER
| Self::ZAR
- | Self::ZMW => false,
+ | Self::ZMW
+ | Self::ZWL => false,
}
}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 00ffb614bb0..21e5866aea0 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -154,3 +154,7 @@ pub const MAX_DESCRIPTION_LENGTH: u16 = 255;
pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22;
/// Payout flow identifier used for performing GSM operations
pub const PAYOUT_FLOW_STR: &str = "payout_flow";
+
+/// The number of bytes allocated for the hashed connector transaction ID.
+/// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2.
+pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25;
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 0cad88bfd4f..855dd179b31 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -1247,3 +1247,129 @@ where
self.0.to_sql(out)
}
}
+
+/// Domain type for connector_transaction_id
+/// Maximum length for connector's transaction_id can be 128 characters in HS DB.
+/// In case connector's use an identifier whose length exceeds 128 characters,
+/// the hash value of such identifiers will be stored as connector_transaction_id.
+/// The actual connector's identifier will be stored in a separate column -
+/// connector_transaction_data or something with a similar name.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
+#[diesel(sql_type = sql_types::Text)]
+pub enum ConnectorTransactionId {
+ /// Actual transaction identifier
+ TxnId(String),
+ /// Hashed value of the transaction identifier
+ HashedData(String),
+}
+
+impl ConnectorTransactionId {
+ /// Implementation for retrieving the inner identifier
+ pub fn get_id(&self) -> &String {
+ match self {
+ Self::TxnId(id) | Self::HashedData(id) => id,
+ }
+ }
+
+ /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and connector_transaction_data
+ pub fn form_id_and_data(src: String) -> (Self, Option<String>) {
+ let txn_id = Self::from(src.clone());
+ match txn_id {
+ Self::TxnId(_) => (txn_id, None),
+ Self::HashedData(_) => (txn_id, Some(src)),
+ }
+ }
+
+ /// Implementation for retrieving
+ pub fn get_txn_id<'a>(
+ &'a self,
+ txn_data: Option<&'a String>,
+ ) -> Result<&'a String, error_stack::Report<ValidationError>> {
+ match (self, txn_data) {
+ (Self::TxnId(id), _) => Ok(id),
+ (Self::HashedData(_), Some(id)) => Ok(id),
+ (Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue {
+ message: "connector_transaction_data is empty for HashedData variant".to_string(),
+ })
+ .attach_printable(format!(
+ "connector_transaction_data is empty for connector_transaction_id {}",
+ id
+ ))),
+ }
+ }
+}
+
+impl From<String> for ConnectorTransactionId {
+ fn from(src: String) -> Self {
+ // ID already hashed
+ if src.starts_with("hs_hash_") {
+ Self::HashedData(src)
+ // Hash connector's transaction ID
+ } else if src.len() > 128 {
+ let mut hasher = blake3::Hasher::new();
+ let mut output = [0u8; consts::CONNECTOR_TRANSACTION_ID_HASH_BYTES];
+ hasher.update(src.as_bytes());
+ hasher.finalize_xof().fill(&mut output);
+ let hash = hex::encode(output);
+ Self::HashedData(format!("hs_hash_{}", hash))
+ // Default
+ } else {
+ Self::TxnId(src)
+ }
+ }
+}
+
+impl<DB> Queryable<sql_types::Text, DB> for ConnectorTransactionId
+where
+ DB: Backend,
+ Self: FromSql<sql_types::Text, DB>,
+{
+ type Row = Self;
+
+ fn build(row: Self::Row) -> deserialize::Result<Self> {
+ Ok(row)
+ }
+}
+
+impl<DB> FromSql<sql_types::Text, DB> for ConnectorTransactionId
+where
+ DB: Backend,
+ String: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
+ let val = String::from_sql(bytes)?;
+ Ok(Self::from(val))
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for ConnectorTransactionId
+where
+ DB: Backend,
+ String: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
+ match self {
+ Self::HashedData(id) | Self::TxnId(id) => id.to_sql(out),
+ }
+ }
+}
+
+/// Trait for fetching actual or hashed transaction IDs
+pub trait ConnectorTransactionIdTrait {
+ /// Returns an optional connector transaction ID
+ fn get_optional_connector_transaction_id(&self) -> Option<&String> {
+ None
+ }
+ /// Returns a connector transaction ID
+ fn get_connector_transaction_id(&self) -> &String {
+ self.get_optional_connector_transaction_id()
+ .unwrap_or_else(|| {
+ static EMPTY_STRING: String = String::new();
+ &EMPTY_STRING
+ })
+ }
+ /// Returns an optional connector refund ID
+ fn get_optional_connector_refund_id(&self) -> Option<&String> {
+ self.get_optional_connector_transaction_id()
+ }
+}
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index f4523cf6171..322186d0e42 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -3410,9 +3410,10 @@ merchant_secret="Source verification key"
payment_method_type = "google_pay"
[[worldpay.wallet]]
payment_method_type = "apple_pay"
-[worldpay.connector_auth.BodyKey]
+[worldpay.connector_auth.SignatureKey]
api_key="Username"
key1="Password"
+api_secret="Merchant Identifier"
[worldpay.connector_webhook_details]
merchant_secret="Source verification key"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index e0d83ff57f5..20faae246e5 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -2469,9 +2469,10 @@ merchant_secret="Source verification key"
payment_method_type = "google_pay"
[[worldpay.wallet]]
payment_method_type = "apple_pay"
-[worldpay.connector_auth.BodyKey]
+[worldpay.connector_auth.SignatureKey]
api_key="Username"
key1="Password"
+api_secret="Merchant Identifier"
[[worldpay.metadata.apple_pay]]
name="certificate"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 80a3af60c49..e7618315b7a 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -3400,9 +3400,10 @@ merchant_secret="Source verification key"
payment_method_type = "google_pay"
[[worldpay.wallet]]
payment_method_type = "apple_pay"
-[worldpay.connector_auth.BodyKey]
+[worldpay.connector_auth.SignatureKey]
api_key="Username"
key1="Password"
+api_secret="Merchant Identifier"
[worldpay.connector_webhook_details]
merchant_secret="Source verification key"
diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs
index a84520dca0a..2001495b2db 100644
--- a/crates/currency_conversion/src/types.rs
+++ b/crates/currency_conversion/src/types.rs
@@ -78,6 +78,7 @@ impl ExchangeRates {
pub fn currency_match(currency: Currency) -> &'static iso::Currency {
match currency {
Currency::AED => iso::AED,
+ Currency::AFN => iso::AFN,
Currency::ALL => iso::ALL,
Currency::AMD => iso::AMD,
Currency::ANG => iso::ANG,
@@ -97,10 +98,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::BOB => iso::BOB,
Currency::BRL => iso::BRL,
Currency::BSD => iso::BSD,
+ Currency::BTN => iso::BTN,
Currency::BWP => iso::BWP,
Currency::BYN => iso::BYN,
Currency::BZD => iso::BZD,
Currency::CAD => iso::CAD,
+ Currency::CDF => iso::CDF,
Currency::CHF => iso::CHF,
Currency::CLP => iso::CLP,
Currency::CNY => iso::CNY,
@@ -114,6 +117,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::DOP => iso::DOP,
Currency::DZD => iso::DZD,
Currency::EGP => iso::EGP,
+ Currency::ERN => iso::ERN,
Currency::ETB => iso::ETB,
Currency::EUR => iso::EUR,
Currency::FJD => iso::FJD,
@@ -135,6 +139,8 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::ILS => iso::ILS,
Currency::INR => iso::INR,
Currency::IQD => iso::IQD,
+ Currency::IRR => iso::IRR,
+ Currency::ISK => iso::ISK,
Currency::JMD => iso::JMD,
Currency::JOD => iso::JOD,
Currency::JPY => iso::JPY,
@@ -142,6 +148,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::KGS => iso::KGS,
Currency::KHR => iso::KHR,
Currency::KMF => iso::KMF,
+ Currency::KPW => iso::KPW,
Currency::KRW => iso::KRW,
Currency::KWD => iso::KWD,
Currency::KYD => iso::KYD,
@@ -188,6 +195,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::SAR => iso::SAR,
Currency::SBD => iso::SBD,
Currency::SCR => iso::SCR,
+ Currency::SDG => iso::SDG,
Currency::SEK => iso::SEK,
Currency::SGD => iso::SGD,
Currency::SHP => iso::SHP,
@@ -198,9 +206,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::SSP => iso::SSP,
Currency::STN => iso::STN,
Currency::SVC => iso::SVC,
+ Currency::SYP => iso::SYP,
Currency::SZL => iso::SZL,
Currency::THB => iso::THB,
+ Currency::TJS => iso::TJS,
Currency::TND => iso::TND,
+ Currency::TMT => iso::TMT,
Currency::TOP => iso::TOP,
Currency::TTD => iso::TTD,
Currency::TRY => iso::TRY,
@@ -222,5 +233,6 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency {
Currency::YER => iso::YER,
Currency::ZAR => iso::ZAR,
Currency::ZMW => iso::ZMW,
+ Currency::ZWL => iso::ZWL,
}
}
diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs
index 0b0b86222e2..d6272c34060 100644
--- a/crates/diesel_models/src/capture.rs
+++ b/crates/diesel_models/src/capture.rs
@@ -1,4 +1,4 @@
-use common_utils::types::MinorUnit;
+use common_utils::types::{ConnectorTransactionId, MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -6,7 +6,7 @@ use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::captures};
#[derive(
- Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash,
+ Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize,
)]
#[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))]
pub struct Capture {
@@ -26,10 +26,11 @@ pub struct Capture {
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
- pub connector_capture_id: Option<String>,
+ pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
// reference to the capture at connector side
pub connector_response_reference_id: Option<String>,
+ pub connector_capture_data: Option<String>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)]
@@ -51,17 +52,19 @@ pub struct CaptureNew {
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
- pub connector_capture_id: Option<String>,
+ pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
pub connector_response_reference_id: Option<String>,
+ pub connector_capture_data: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CaptureUpdate {
ResponseUpdate {
status: storage_enums::CaptureStatus,
- connector_capture_id: Option<String>,
+ connector_capture_id: Option<ConnectorTransactionId>,
connector_response_reference_id: Option<String>,
+ connector_capture_data: Option<String>,
},
ErrorUpdate {
status: storage_enums::CaptureStatus,
@@ -79,8 +82,9 @@ pub struct CaptureUpdateInternal {
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub modified_at: Option<PrimitiveDateTime>,
- pub connector_capture_id: Option<String>,
+ pub connector_capture_id: Option<ConnectorTransactionId>,
pub connector_response_reference_id: Option<String>,
+ pub connector_capture_data: Option<String>,
}
impl CaptureUpdate {
@@ -93,6 +97,7 @@ impl CaptureUpdate {
modified_at: _,
connector_capture_id,
connector_response_reference_id,
+ connector_capture_data,
} = self.into();
Capture {
status: status.unwrap_or(source.status),
@@ -103,6 +108,7 @@ impl CaptureUpdate {
connector_capture_id: connector_capture_id.or(source.connector_capture_id),
connector_response_reference_id: connector_response_reference_id
.or(source.connector_response_reference_id),
+ connector_capture_data: connector_capture_data.or(source.connector_capture_data),
..source
}
}
@@ -116,11 +122,13 @@ impl From<CaptureUpdate> for CaptureUpdateInternal {
status,
connector_capture_id: connector_transaction_id,
connector_response_reference_id,
+ connector_capture_data,
} => Self {
status: Some(status),
connector_capture_id: connector_transaction_id,
modified_at: now,
connector_response_reference_id,
+ connector_capture_data,
..Self::default()
},
CaptureUpdate::ErrorUpdate {
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 20551c2754b..277061c78aa 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -1,4 +1,7 @@
-use common_utils::{id_type, pii, types::MinorUnit};
+use common_utils::{
+ id_type, pii,
+ types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
+};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -63,12 +66,13 @@ pub struct PaymentAttempt {
pub organization_id: id_type::OrganizationId,
pub card_network: Option<String>,
pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,
- pub connector_payment_id: Option<String>,
+ pub connector_payment_id: Option<ConnectorTransactionId>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
+ pub connector_payment_data: Option<String>,
pub id: String,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
@@ -94,7 +98,7 @@ pub struct PaymentAttempt {
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
- pub connector_transaction_id: Option<String>,
+ pub connector_transaction_id: Option<ConnectorTransactionId>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
@@ -148,6 +152,47 @@ pub struct PaymentAttempt {
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_transaction_data: Option<String>,
+}
+
+#[cfg(feature = "v1")]
+impl ConnectorTransactionIdTrait for PaymentAttempt {
+ fn get_optional_connector_transaction_id(&self) -> Option<&String> {
+ match self
+ .connector_transaction_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_txn_id(self.connector_transaction_data.as_ref()))
+ .transpose()
+ {
+ Ok(txn_id) => txn_id,
+
+ // In case hashed data is missing from DB, use the hashed ID as connector transaction ID
+ Err(_) => self
+ .connector_transaction_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_id()),
+ }
+ }
+}
+
+#[cfg(feature = "v2")]
+impl ConnectorTransactionIdTrait for PaymentAttempt {
+ fn get_optional_connector_transaction_id(&self) -> Option<&String> {
+ match self
+ .connector_payment_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_txn_id(self.connector_payment_data.as_ref()))
+ .transpose()
+ {
+ Ok(txn_id) => txn_id,
+
+ // In case hashed data is missing from DB, use the hashed ID as connector payment ID
+ Err(_) => self
+ .connector_payment_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_id()),
+ }
+ }
}
#[derive(Clone, Debug, Eq, PartialEq, Queryable, Serialize, Deserialize)]
@@ -711,6 +756,7 @@ pub struct PaymentAttemptUpdateInternal {
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
card_network: Option<String>,
+ connector_payment_data: Option<String>,
}
#[cfg(feature = "v1")]
@@ -721,7 +767,7 @@ pub struct PaymentAttemptUpdateInternal {
pub net_amount: Option<MinorUnit>,
pub currency: Option<storage_enums::Currency>,
pub status: Option<storage_enums::AttemptStatus>,
- pub connector_transaction_id: Option<String>,
+ pub connector_transaction_id: Option<ConnectorTransactionId>,
pub amount_to_capture: Option<MinorUnit>,
pub connector: Option<Option<String>>,
pub authentication_type: Option<storage_enums::AuthenticationType>,
@@ -766,6 +812,7 @@ pub struct PaymentAttemptUpdateInternal {
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
@@ -954,6 +1001,7 @@ impl PaymentAttemptUpdate {
card_network,
shipping_cost,
order_tax_amount,
+ connector_transaction_data,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -1009,6 +1057,8 @@ impl PaymentAttemptUpdate {
card_network: card_network.or(source.card_network),
shipping_cost: shipping_cost.or(source.shipping_cost),
order_tax_amount: order_tax_amount.or(source.order_tax_amount),
+ connector_transaction_data: connector_transaction_data
+ .or(source.connector_transaction_data),
..source
}
}
@@ -2003,6 +2053,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -2057,6 +2108,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -2141,6 +2193,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost,
order_tax_amount,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -2196,6 +2249,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -2252,6 +2306,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -2308,6 +2363,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -2362,6 +2418,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -2384,57 +2441,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_message,
payment_method_data,
charge_id,
- } => Self {
- status: Some(status),
- connector: connector.map(Some),
- connector_transaction_id,
- authentication_type,
- payment_method_id,
- modified_at: common_utils::date_time::now(),
- mandate_id,
- connector_metadata,
- error_code,
- error_message,
- payment_token,
- error_reason,
- connector_response_reference_id,
- amount_capturable,
- updated_by,
- authentication_data,
- encoded_data,
- unified_code,
- unified_message,
- payment_method_data,
- charge_id,
- amount: None,
- net_amount: None,
- currency: None,
- amount_to_capture: None,
- payment_method: None,
- cancellation_reason: None,
- browser_info: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- preprocessing_step_id: None,
- capture_method: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- merchant_connector_id: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ status: Some(status),
+ connector: connector.map(Some),
+ connector_transaction_id,
+ authentication_type,
+ payment_method_id,
+ modified_at: common_utils::date_time::now(),
+ mandate_id,
+ connector_metadata,
+ error_code,
+ error_message,
+ payment_token,
+ error_reason,
+ connector_response_reference_id,
+ amount_capturable,
+ updated_by,
+ authentication_data,
+ encoded_data,
+ unified_code,
+ unified_message,
+ payment_method_data,
+ charge_id,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ amount_to_capture: None,
+ payment_method: None,
+ cancellation_reason: None,
+ browser_info: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ preprocessing_step_id: None,
+ capture_method: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ merchant_connector_id: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::ErrorUpdate {
connector,
status,
@@ -2448,57 +2513,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_transaction_id,
payment_method_data,
authentication_type,
- } => Self {
- connector: connector.map(Some),
- status: Some(status),
- error_message,
- error_code,
- modified_at: common_utils::date_time::now(),
- error_reason,
- amount_capturable,
- updated_by,
- unified_code,
- unified_message,
- connector_transaction_id,
- payment_method_data,
- authentication_type,
- amount: None,
- net_amount: None,
- currency: None,
- amount_to_capture: None,
- payment_method: None,
- payment_method_id: None,
- cancellation_reason: None,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- connector_metadata: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- preprocessing_step_id: None,
- capture_method: None,
- connector_response_reference_id: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- merchant_connector_id: None,
- authentication_data: None,
- encoded_data: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- charge_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ connector: connector.map(Some),
+ status: Some(status),
+ error_message,
+ error_code,
+ modified_at: common_utils::date_time::now(),
+ error_reason,
+ amount_capturable,
+ updated_by,
+ unified_code,
+ unified_message,
+ connector_transaction_id,
+ payment_method_data,
+ authentication_type,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ amount_to_capture: None,
+ payment_method: None,
+ payment_method_id: None,
+ cancellation_reason: None,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ connector_metadata: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ preprocessing_step_id: None,
+ capture_method: None,
+ connector_response_reference_id: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ merchant_connector_id: None,
+ authentication_data: None,
+ encoded_data: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ charge_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
status: Some(status),
modified_at: common_utils::date_time::now(),
@@ -2549,6 +2622,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -2609,6 +2683,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -2620,57 +2695,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
error_reason,
connector_response_reference_id,
updated_by,
- } => Self {
- status: Some(status),
- connector: connector.map(Some),
- connector_transaction_id,
- payment_method_id,
- modified_at: common_utils::date_time::now(),
- error_code,
- error_message,
- error_reason,
- connector_response_reference_id,
- updated_by,
- amount: None,
- net_amount: None,
- currency: None,
- amount_to_capture: None,
- authentication_type: None,
- payment_method: None,
- cancellation_reason: None,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- connector_metadata: None,
- payment_method_data: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- preprocessing_step_id: None,
- capture_method: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- amount_capturable: None,
- merchant_connector_id: None,
- authentication_data: None,
- encoded_data: None,
- unified_code: None,
- unified_message: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- charge_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ status: Some(status),
+ connector: connector.map(Some),
+ connector_transaction_id,
+ payment_method_id,
+ modified_at: common_utils::date_time::now(),
+ error_code,
+ error_message,
+ error_reason,
+ connector_response_reference_id,
+ updated_by,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ amount_to_capture: None,
+ authentication_type: None,
+ payment_method: None,
+ cancellation_reason: None,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ connector_metadata: None,
+ payment_method_data: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ preprocessing_step_id: None,
+ capture_method: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ amount_capturable: None,
+ merchant_connector_id: None,
+ authentication_data: None,
+ encoded_data: None,
+ unified_code: None,
+ unified_message: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ charge_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::PreprocessingUpdate {
status,
payment_method_id,
@@ -2679,57 +2762,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_transaction_id,
connector_response_reference_id,
updated_by,
- } => Self {
- status: Some(status),
- payment_method_id,
- modified_at: common_utils::date_time::now(),
- connector_metadata,
- preprocessing_step_id,
- connector_transaction_id,
- connector_response_reference_id,
- updated_by,
- amount: None,
- net_amount: None,
- currency: None,
- amount_to_capture: None,
- connector: None,
- authentication_type: None,
- payment_method: None,
- error_message: None,
- cancellation_reason: None,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- error_code: None,
- payment_method_data: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- error_reason: None,
- capture_method: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- amount_capturable: None,
- merchant_connector_id: None,
- authentication_data: None,
- encoded_data: None,
- unified_code: None,
- unified_message: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- charge_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ status: Some(status),
+ payment_method_id,
+ modified_at: common_utils::date_time::now(),
+ connector_metadata,
+ preprocessing_step_id,
+ connector_transaction_id,
+ connector_response_reference_id,
+ updated_by,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ amount_to_capture: None,
+ connector: None,
+ authentication_type: None,
+ payment_method: None,
+ error_message: None,
+ cancellation_reason: None,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ error_code: None,
+ payment_method_data: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ error_reason: None,
+ capture_method: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ amount_capturable: None,
+ merchant_connector_id: None,
+ authentication_data: None,
+ encoded_data: None,
+ unified_code: None,
+ unified_message: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ charge_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
updated_by,
@@ -2784,6 +2875,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -2839,6 +2931,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -2847,57 +2940,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector,
updated_by,
charge_id,
- } => Self {
- authentication_data,
- encoded_data,
- connector_transaction_id,
- connector: connector.map(Some),
- modified_at: common_utils::date_time::now(),
- updated_by,
- charge_id,
- amount: None,
- net_amount: None,
- currency: None,
- status: None,
- amount_to_capture: None,
- authentication_type: None,
- payment_method: None,
- error_message: None,
- payment_method_id: None,
- cancellation_reason: None,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- error_code: None,
- connector_metadata: None,
- payment_method_data: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- preprocessing_step_id: None,
- error_reason: None,
- capture_method: None,
- connector_response_reference_id: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- amount_capturable: None,
- merchant_connector_id: None,
- unified_code: None,
- unified_message: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ authentication_data,
+ encoded_data,
+ connector_transaction_id,
+ connector: connector.map(Some),
+ modified_at: common_utils::date_time::now(),
+ updated_by,
+ charge_id,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ status: None,
+ amount_to_capture: None,
+ authentication_type: None,
+ payment_method: None,
+ error_message: None,
+ payment_method_id: None,
+ cancellation_reason: None,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ error_code: None,
+ connector_metadata: None,
+ payment_method_data: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ preprocessing_step_id: None,
+ error_reason: None,
+ capture_method: None,
+ connector_response_reference_id: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ amount_capturable: None,
+ merchant_connector_id: None,
+ unified_code: None,
+ unified_message: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount,
amount_capturable,
@@ -2951,6 +3052,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -3008,6 +3110,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -3018,57 +3121,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_code,
unified_message,
connector_transaction_id,
- } => Self {
- status,
- error_code: error_code.map(Some),
- modified_at: common_utils::date_time::now(),
- error_message: error_message.map(Some),
- error_reason: error_reason.map(Some),
- updated_by,
- unified_code: unified_code.map(Some),
- unified_message: unified_message.map(Some),
- amount: None,
- net_amount: None,
- currency: None,
- connector_transaction_id,
- amount_to_capture: None,
- connector: None,
- authentication_type: None,
- payment_method: None,
- payment_method_id: None,
- cancellation_reason: None,
- mandate_id: None,
- browser_info: None,
- payment_token: None,
- connector_metadata: None,
- payment_method_data: None,
- payment_method_type: None,
- payment_experience: None,
- business_sub_label: None,
- straight_through_algorithm: None,
- preprocessing_step_id: None,
- capture_method: None,
- connector_response_reference_id: None,
- multiple_capture_count: None,
- surcharge_amount: None,
- tax_amount: None,
- amount_capturable: None,
- merchant_connector_id: None,
- authentication_data: None,
- encoded_data: None,
- external_three_ds_authentication_attempted: None,
- authentication_connector: None,
- authentication_id: None,
- fingerprint_id: None,
- payment_method_billing_address_id: None,
- charge_id: None,
- client_source: None,
- client_version: None,
- customer_acceptance: None,
- card_network: None,
- shipping_cost: None,
- order_tax_amount: None,
- },
+ } => {
+ let (connector_transaction_id, connector_transaction_data) =
+ connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+ Self {
+ status,
+ error_code: error_code.map(Some),
+ modified_at: common_utils::date_time::now(),
+ error_message: error_message.map(Some),
+ error_reason: error_reason.map(Some),
+ updated_by,
+ unified_code: unified_code.map(Some),
+ unified_message: unified_message.map(Some),
+ connector_transaction_id,
+ connector_transaction_data,
+ amount: None,
+ net_amount: None,
+ currency: None,
+ amount_to_capture: None,
+ connector: None,
+ authentication_type: None,
+ payment_method: None,
+ payment_method_id: None,
+ cancellation_reason: None,
+ mandate_id: None,
+ browser_info: None,
+ payment_token: None,
+ connector_metadata: None,
+ payment_method_data: None,
+ payment_method_type: None,
+ payment_experience: None,
+ business_sub_label: None,
+ straight_through_algorithm: None,
+ preprocessing_step_id: None,
+ capture_method: None,
+ connector_response_reference_id: None,
+ multiple_capture_count: None,
+ surcharge_amount: None,
+ tax_amount: None,
+ amount_capturable: None,
+ merchant_connector_id: None,
+ authentication_data: None,
+ encoded_data: None,
+ external_three_ds_authentication_attempted: None,
+ authentication_connector: None,
+ authentication_id: None,
+ fingerprint_id: None,
+ payment_method_billing_address_id: None,
+ charge_id: None,
+ client_source: None,
+ client_version: None,
+ customer_acceptance: None,
+ card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
+ }
+ }
PaymentAttemptUpdate::PostSessionTokensUpdate {
updated_by,
connector_metadata,
@@ -3122,6 +3233,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data: None,
},
}
}
diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs
index e194dc9f64c..7a32e410961 100644
--- a/crates/diesel_models/src/query/capture.rs
+++ b/crates/diesel_models/src/query/capture.rs
@@ -1,3 +1,4 @@
+use common_utils::types::ConnectorTransactionIdTrait;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
@@ -67,3 +68,22 @@ impl Capture {
.await
}
}
+
+impl ConnectorTransactionIdTrait for Capture {
+ fn get_optional_connector_transaction_id(&self) -> Option<&String> {
+ match self
+ .connector_capture_id
+ .as_ref()
+ .map(|capture_id| capture_id.get_txn_id(self.connector_capture_data.as_ref()))
+ .transpose()
+ {
+ Ok(capture_id) => capture_id,
+
+ // In case hashed data is missing from DB, use the hashed ID as connector transaction ID
+ Err(_) => self
+ .connector_capture_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_id()),
+ }
+ }
+}
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 42b0ffa620c..9e850bc9f1f 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -1,6 +1,6 @@
use common_utils::{
pii,
- types::{ChargeRefunds, MinorUnit},
+ types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
@@ -25,9 +25,9 @@ pub struct Refund {
pub refund_id: String, //merchant_reference id
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
- pub connector_transaction_id: String,
+ pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
- pub connector_refund_id: Option<String>,
+ pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
@@ -51,6 +51,8 @@ pub struct Refund {
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: common_utils::id_type::OrganizationId,
+ pub connector_refund_data: Option<String>,
+ pub connector_transaction_data: Option<String>,
}
#[derive(
@@ -71,9 +73,9 @@ pub struct RefundNew {
pub merchant_id: common_utils::id_type::MerchantId,
pub internal_reference_id: String,
pub external_reference_id: Option<String>,
- pub connector_transaction_id: String,
+ pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
- pub connector_refund_id: Option<String>,
+ pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
@@ -94,17 +96,20 @@ pub struct RefundNew {
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: common_utils::id_type::OrganizationId,
+ pub connector_refund_data: Option<String>,
+ pub connector_transaction_data: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
- connector_refund_id: String,
+ connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
+ connector_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
@@ -112,17 +117,19 @@ pub enum RefundUpdate {
updated_by: String,
},
StatusUpdate {
- connector_refund_id: Option<String>,
+ connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
+ connector_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
- connector_refund_id: Option<String>,
+ connector_refund_id: Option<ConnectorTransactionId>,
+ connector_refund_data: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
@@ -135,7 +142,7 @@ pub enum RefundUpdate {
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
- connector_refund_id: Option<String>,
+ connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
@@ -145,6 +152,7 @@ pub struct RefundUpdateInternal {
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
+ connector_refund_data: Option<String>,
}
impl RefundUpdateInternal {
@@ -160,6 +168,7 @@ impl RefundUpdateInternal {
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
+ connector_refund_data: self.connector_refund_data,
..source
}
}
@@ -175,6 +184,7 @@ impl From<RefundUpdate> for RefundUpdateInternal {
refund_error_message,
refund_arn,
updated_by,
+ connector_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
@@ -182,6 +192,7 @@ impl From<RefundUpdate> for RefundUpdateInternal {
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
+ connector_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
@@ -202,17 +213,20 @@ impl From<RefundUpdate> for RefundUpdateInternal {
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
+ connector_refund_data: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
+ connector_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
+ connector_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
@@ -226,12 +240,14 @@ impl From<RefundUpdate> for RefundUpdateInternal {
refund_error_code,
updated_by,
connector_refund_id,
+ connector_refund_data,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
+ connector_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
@@ -254,6 +270,7 @@ impl From<RefundUpdate> for RefundUpdateInternal {
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
+ connector_refund_data: None,
},
}
}
@@ -272,6 +289,7 @@ impl RefundUpdate {
refund_error_code,
updated_by,
modified_at: _,
+ connector_refund_data,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
@@ -284,6 +302,7 @@ impl RefundUpdate {
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
+ connector_refund_data: connector_refund_data.or(source.connector_refund_data),
..source
}
}
@@ -292,9 +311,10 @@ impl RefundUpdate {
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_internal_reference_id: String,
- pub connector_transaction_id: String,
+ pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: common_utils::id_type::PaymentId,
+ pub connector_transaction_data: Option<String>,
}
impl common_utils::events::ApiEventMetric for Refund {
@@ -306,6 +326,37 @@ impl common_utils::events::ApiEventMetric for Refund {
}
}
+impl ConnectorTransactionIdTrait for Refund {
+ fn get_optional_connector_refund_id(&self) -> Option<&String> {
+ match self
+ .connector_refund_id
+ .as_ref()
+ .map(|refund_id| refund_id.get_txn_id(self.connector_refund_data.as_ref()))
+ .transpose()
+ {
+ Ok(refund_id) => refund_id,
+
+ // In case hashed data is missing from DB, use the hashed ID as connector transaction ID
+ Err(_) => self
+ .connector_refund_id
+ .as_ref()
+ .map(|txn_id| txn_id.get_id()),
+ }
+ }
+
+ fn get_connector_transaction_id(&self) -> &String {
+ match self
+ .connector_transaction_id
+ .get_txn_id(self.connector_transaction_data.as_ref())
+ {
+ Ok(txn_id) => txn_id,
+
+ // In case hashed data is missing from DB, use the hashed ID as connector transaction ID
+ Err(_) => self.connector_transaction_id.get_id(),
+ }
+ }
+}
+
mod tests {
#[test]
fn test_backwards_compatibility() {
@@ -336,7 +387,8 @@ mod tests {
"profile_id": null,
"updated_by": "admin",
"merchant_connector_id": null,
- "charges": null
+ "charges": null,
+ "connector_transaction_data": null
}"#;
let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index a9e0b54260c..5cd2abd3599 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -248,6 +248,8 @@ diesel::table! {
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
+ #[max_length = 512]
+ connector_capture_data -> Nullable<Varchar>,
}
}
@@ -846,6 +848,8 @@ diesel::table! {
card_network -> Nullable<Varchar>,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
+ #[max_length = 512]
+ connector_transaction_data -> Nullable<Varchar>,
}
}
@@ -1183,6 +1187,10 @@ diesel::table! {
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
+ #[max_length = 512]
+ connector_refund_data -> Nullable<Varchar>,
+ #[max_length = 512]
+ connector_transaction_data -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 53f568f18c4..99a4453bba2 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -255,6 +255,8 @@ diesel::table! {
capture_sequence -> Int2,
#[max_length = 128]
connector_response_reference_id -> Nullable<Varchar>,
+ #[max_length = 512]
+ connector_capture_data -> Nullable<Varchar>,
}
}
@@ -813,6 +815,8 @@ diesel::table! {
#[max_length = 128]
external_reference_id -> Nullable<Varchar>,
tax_on_surcharge -> Nullable<Int8>,
+ #[max_length = 512]
+ connector_payment_data -> Nullable<Varchar>,
#[max_length = 64]
id -> Varchar,
shipping_cost -> Nullable<Int8>,
@@ -1130,6 +1134,10 @@ diesel::table! {
charges -> Nullable<Jsonb>,
#[max_length = 32]
organization_id -> Varchar,
+ #[max_length = 512]
+ connector_refund_data -> Nullable<Varchar>,
+ #[max_length = 512]
+ connector_transaction_data -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index a354e4a02ab..db30d02bd7c 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -2,7 +2,7 @@ use common_enums::{
AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod,
PaymentMethodType,
};
-use common_utils::types::MinorUnit;
+use common_utils::types::{ConnectorTransactionId, MinorUnit};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -179,7 +179,7 @@ pub struct PaymentAttemptBatchNew {
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
- pub connector_transaction_id: Option<String>,
+ pub connector_transaction_id: Option<ConnectorTransactionId>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
@@ -203,6 +203,7 @@ pub struct PaymentAttemptBatchNew {
pub organization_id: common_utils::id_type::OrganizationId,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 5aba0616143..42216b9f78f 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -6,7 +6,7 @@ use common_utils::{
id_type, pii,
types::{
keymanager::{self, KeyManagerState},
- MinorUnit,
+ ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit,
},
};
use diesel_models::{
@@ -1212,6 +1212,11 @@ impl behaviour::Conversion for PaymentAttempt {
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string());
+ let (connector_transaction_id, connector_transaction_data) = self
+ .connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
Ok(DieselPaymentAttempt {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
@@ -1227,7 +1232,7 @@ impl behaviour::Conversion for PaymentAttempt {
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
- connector_transaction_id: self.connector_transaction_id,
+ connector_transaction_id,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
@@ -1274,6 +1279,7 @@ impl behaviour::Conversion for PaymentAttempt {
profile_id: self.profile_id,
organization_id: self.organization_id,
card_network,
+ connector_transaction_data,
order_tax_amount: self.net_amount.get_order_tax_amount(),
shipping_cost: self.net_amount.get_shipping_cost(),
})
@@ -1289,6 +1295,9 @@ impl behaviour::Conversion for PaymentAttempt {
Self: Sized,
{
async {
+ let connector_transaction_id = storage_model
+ .get_optional_connector_transaction_id()
+ .cloned();
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
@@ -1308,7 +1317,7 @@ impl behaviour::Conversion for PaymentAttempt {
offer_amount: storage_model.offer_amount,
payment_method_id: storage_model.payment_method_id,
payment_method: storage_model.payment_method,
- connector_transaction_id: storage_model.connector_transaction_id,
+ connector_transaction_id,
capture_method: storage_model.capture_method,
capture_on: storage_model.capture_on,
confirm: storage_model.confirm,
@@ -1511,6 +1520,11 @@ impl behaviour::Conversion for PaymentAttempt {
connector,
} = self;
+ let (connector_payment_id, connector_payment_data) = connector_payment_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
+
Ok(DieselPaymentAttempt {
payment_id,
merchant_id,
@@ -1566,6 +1580,7 @@ impl behaviour::Conversion for PaymentAttempt {
authentication_applied,
external_reference_id,
connector,
+ connector_payment_data,
})
}
@@ -1579,6 +1594,9 @@ impl behaviour::Conversion for PaymentAttempt {
Self: Sized,
{
async {
+ let connector_payment_id = storage_model
+ .get_optional_connector_transaction_id()
+ .cloned();
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
@@ -1590,7 +1608,7 @@ impl behaviour::Conversion for PaymentAttempt {
surcharge_amount: storage_model.surcharge_amount,
payment_method_id: storage_model.payment_method_id,
payment_method_type: storage_model.payment_method_type_v2,
- connector_payment_id: storage_model.connector_payment_id,
+ connector_payment_id,
confirm: storage_model.confirm,
authentication_type: storage_model.authentication_type,
created_at: storage_model.created_at,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index d599a2caa74..39047f7015a 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -118,6 +118,7 @@ pub struct PaymentsCaptureData {
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
+ pub capture_method: Option<storage_enums::CaptureMethod>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs
index 1a340aa91d3..3aaeb0586d6 100644
--- a/crates/kgraph_utils/src/transformers.rs
+++ b/crates/kgraph_utils/src/transformers.rs
@@ -334,6 +334,7 @@ impl IntoDirValue for api_enums::Currency {
fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> {
match self {
Self::AED => Ok(dirval!(PaymentCurrency = AED)),
+ Self::AFN => Ok(dirval!(PaymentCurrency = AFN)),
Self::ALL => Ok(dirval!(PaymentCurrency = ALL)),
Self::AMD => Ok(dirval!(PaymentCurrency = AMD)),
Self::ANG => Ok(dirval!(PaymentCurrency = ANG)),
@@ -353,10 +354,12 @@ impl IntoDirValue for api_enums::Currency {
Self::BOB => Ok(dirval!(PaymentCurrency = BOB)),
Self::BRL => Ok(dirval!(PaymentCurrency = BRL)),
Self::BSD => Ok(dirval!(PaymentCurrency = BSD)),
+ Self::BTN => Ok(dirval!(PaymentCurrency = BTN)),
Self::BWP => Ok(dirval!(PaymentCurrency = BWP)),
Self::BYN => Ok(dirval!(PaymentCurrency = BYN)),
Self::BZD => Ok(dirval!(PaymentCurrency = BZD)),
Self::CAD => Ok(dirval!(PaymentCurrency = CAD)),
+ Self::CDF => Ok(dirval!(PaymentCurrency = CDF)),
Self::CHF => Ok(dirval!(PaymentCurrency = CHF)),
Self::CLP => Ok(dirval!(PaymentCurrency = CLP)),
Self::CNY => Ok(dirval!(PaymentCurrency = CNY)),
@@ -370,6 +373,7 @@ impl IntoDirValue for api_enums::Currency {
Self::DOP => Ok(dirval!(PaymentCurrency = DOP)),
Self::DZD => Ok(dirval!(PaymentCurrency = DZD)),
Self::EGP => Ok(dirval!(PaymentCurrency = EGP)),
+ Self::ERN => Ok(dirval!(PaymentCurrency = ERN)),
Self::ETB => Ok(dirval!(PaymentCurrency = ETB)),
Self::EUR => Ok(dirval!(PaymentCurrency = EUR)),
Self::FJD => Ok(dirval!(PaymentCurrency = FJD)),
@@ -391,6 +395,8 @@ impl IntoDirValue for api_enums::Currency {
Self::ILS => Ok(dirval!(PaymentCurrency = ILS)),
Self::INR => Ok(dirval!(PaymentCurrency = INR)),
Self::IQD => Ok(dirval!(PaymentCurrency = IQD)),
+ Self::IRR => Ok(dirval!(PaymentCurrency = IRR)),
+ Self::ISK => Ok(dirval!(PaymentCurrency = ISK)),
Self::JMD => Ok(dirval!(PaymentCurrency = JMD)),
Self::JOD => Ok(dirval!(PaymentCurrency = JOD)),
Self::JPY => Ok(dirval!(PaymentCurrency = JPY)),
@@ -398,6 +404,7 @@ impl IntoDirValue for api_enums::Currency {
Self::KGS => Ok(dirval!(PaymentCurrency = KGS)),
Self::KHR => Ok(dirval!(PaymentCurrency = KHR)),
Self::KMF => Ok(dirval!(PaymentCurrency = KMF)),
+ Self::KPW => Ok(dirval!(PaymentCurrency = KPW)),
Self::KRW => Ok(dirval!(PaymentCurrency = KRW)),
Self::KWD => Ok(dirval!(PaymentCurrency = KWD)),
Self::KYD => Ok(dirval!(PaymentCurrency = KYD)),
@@ -444,6 +451,7 @@ impl IntoDirValue for api_enums::Currency {
Self::SAR => Ok(dirval!(PaymentCurrency = SAR)),
Self::SBD => Ok(dirval!(PaymentCurrency = SBD)),
Self::SCR => Ok(dirval!(PaymentCurrency = SCR)),
+ Self::SDG => Ok(dirval!(PaymentCurrency = SDG)),
Self::SEK => Ok(dirval!(PaymentCurrency = SEK)),
Self::SGD => Ok(dirval!(PaymentCurrency = SGD)),
Self::SHP => Ok(dirval!(PaymentCurrency = SHP)),
@@ -454,8 +462,11 @@ impl IntoDirValue for api_enums::Currency {
Self::SSP => Ok(dirval!(PaymentCurrency = SSP)),
Self::STN => Ok(dirval!(PaymentCurrency = STN)),
Self::SVC => Ok(dirval!(PaymentCurrency = SVC)),
+ Self::SYP => Ok(dirval!(PaymentCurrency = SYP)),
Self::SZL => Ok(dirval!(PaymentCurrency = SZL)),
Self::THB => Ok(dirval!(PaymentCurrency = THB)),
+ Self::TJS => Ok(dirval!(PaymentCurrency = TJS)),
+ Self::TMT => Ok(dirval!(PaymentCurrency = TMT)),
Self::TND => Ok(dirval!(PaymentCurrency = TND)),
Self::TOP => Ok(dirval!(PaymentCurrency = TOP)),
Self::TRY => Ok(dirval!(PaymentCurrency = TRY)),
@@ -478,6 +489,7 @@ impl IntoDirValue for api_enums::Currency {
Self::YER => Ok(dirval!(PaymentCurrency = YER)),
Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)),
Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)),
+ Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)),
}
}
}
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 33c9393cede..b5469f12c16 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -2,9 +2,12 @@ mod requests;
mod response;
pub mod transformers;
-use std::fmt::Debug;
-
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
+use common_utils::{
+ crypto,
+ ext_traits::ByteSliceExt,
+ request::RequestContent,
+ types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
+};
use diesel_models::enums;
use error_stack::ResultExt;
use transformers as worldpay;
@@ -30,8 +33,18 @@ use crate::{
utils::BytesExt,
};
-#[derive(Debug, Clone)]
-pub struct Worldpay;
+#[derive(Clone)]
+pub struct Worldpay {
+ amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
+}
+
+impl Worldpay {
+ pub const fn new() -> &'static Self {
+ &Self {
+ amount_converter: &MinorUnitForConnector,
+ }
+ }
+}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpay
where
@@ -42,10 +55,16 @@ where
req: &types::RouterData<Flow, Request, Response>,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut headers = vec![(
- headers::CONTENT_TYPE.to_string(),
- self.get_content_type().to_string().into(),
- )];
+ let mut headers = vec![
+ (
+ headers::ACCEPT.to_string(),
+ self.get_content_type().to_string().into(),
+ ),
+ (
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ ),
+ ];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut api_key);
Ok(headers)
@@ -62,7 +81,7 @@ impl ConnectorCommon for Worldpay {
}
fn common_get_content_type(&self) -> &'static str {
- "application/vnd.worldpay.payments-v6+json"
+ "application/vnd.worldpay.payments-v7+json"
}
fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
@@ -86,10 +105,13 @@ impl ConnectorCommon for Worldpay {
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: WorldpayErrorResponse = res
- .response
- .parse_struct("WorldpayErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let response = if !res.response.is_empty() {
+ res.response
+ .parse_struct("WorldpayErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?
+ } else {
+ WorldpayErrorResponse::default(res.status_code)
+ };
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -183,9 +205,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
- "{}payments/settlements/{}",
+ "{}payments/authorizations/cancellations/{connector_payment_id}",
self.base_url(connectors),
- connector_payment_id
))
}
@@ -328,8 +349,22 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+ let attempt_status = data.status;
+ let worldpay_status = response.last_event;
+ let status = match (attempt_status, worldpay_status.clone()) {
+ (
+ enums::AttemptStatus::Authorizing
+ | enums::AttemptStatus::Authorized
+ | enums::AttemptStatus::CaptureInitiated
+ | enums::AttemptStatus::Pending
+ | enums::AttemptStatus::VoidInitiated,
+ EventType::Authorized,
+ ) => attempt_status,
+ _ => enums::AttemptStatus::from(&worldpay_status),
+ };
+
Ok(types::PaymentsSyncRouterData {
- status: enums::AttemptStatus::from(response.last_event),
+ status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: data.request.connector_transaction_id.clone(),
redirection_data: None,
@@ -361,6 +396,33 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
self.common_get_content_type()
}
+ fn get_url(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}payments/settlements/partials/{}",
+ self.base_url(connectors),
+ connector_payment_id
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount_to_capture = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+ let connector_req = WorldpayPartialRequest::try_from((req, amount_to_capture))?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
fn build_request(
&self,
req: &types::PaymentsCaptureRouterData,
@@ -374,6 +436,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
.build(),
))
}
@@ -393,7 +458,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(types::PaymentsCaptureRouterData {
- status: enums::AttemptStatus::Charged,
+ status: enums::AttemptStatus::Pending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::foreign_try_from(response.links)?,
redirection_data: None,
@@ -411,19 +476,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
- fn get_url(
- &self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- let connector_payment_id = req.request.connector_transaction_id.clone();
- Ok(format!(
- "{}payments/settlements/{}",
- self.base_url(connectors),
- connector_payment_id
- ))
- }
-
fn get_error_response(
&self,
res: Response,
@@ -463,7 +515,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
- "{}payments/authorizations",
+ "{}cardPayments/customerInitiatedTransactions",
self.base_url(connectors)
))
}
@@ -476,10 +528,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
let connector_router_data = worldpay::WorldpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
- req.request.amount,
+ req.request.minor_amount,
req,
))?;
- let connector_req = WorldpayPaymentsRequest::try_from(&connector_router_data)?;
+ let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let connector_req =
+ WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -560,7 +615,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundExecuteRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = WorldpayRefundRequest::try_from(req)?;
+ let amount_to_refund = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+ let connector_req = WorldpayPartialRequest::try_from((req, amount_to_refund))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -613,7 +673,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
Ok(types::RefundExecuteRouterData {
response: Ok(types::RefundsResponseData {
connector_refund_id: ResponseIdStr::try_from(response.links)?.id,
- refund_status: enums::RefundStatus::Success,
+ refund_status: enums::RefundStatus::Pending,
}),
..data.clone()
})
@@ -766,19 +826,20 @@ impl api::IncomingWebhook for Worldpay {
.parse_struct("WorldpayWebhookEventType")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match body.event_details.event_type {
- EventType::SentForSettlement | EventType::Charged => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ EventType::Authorized => {
+ Ok(api::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
- EventType::Error | EventType::Expired => {
+ EventType::SentForSettlement => Ok(api::IncomingWebhookEvent::PaymentIntentProcessing),
+ EventType::Settled => Ok(api::IncomingWebhookEvent::PaymentIntentSuccess),
+ EventType::Error | EventType::Expired | EventType::SettlementFailed => {
Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
}
EventType::Unknown
- | EventType::Authorized
+ | EventType::SentForAuthorization
| EventType::Cancelled
| EventType::Refused
| EventType::Refunded
| EventType::SentForRefund
- | EventType::CaptureFailed
| EventType::RefundFailed => Ok(api::IncomingWebhookEvent::EventNotSupported),
}
}
diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs
index 5fb5d75d940..301ae64946d 100644
--- a/crates/router/src/connector/worldpay/requests.rs
+++ b/crates/router/src/connector/worldpay/requests.rs
@@ -4,29 +4,28 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
#[serde(skip_serializing_if = "Option::is_none")]
- pub city: Option<String>,
+ pub address1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address2: Option<Secret<String>>,
- pub postal_code: Secret<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address3: Option<Secret<String>>,
- pub country_code: common_enums::CountryAlpha2,
#[serde(skip_serializing_if = "Option::is_none")]
- pub address1: Option<Secret<String>>,
+ pub city: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub state: Option<Secret<String>>,
+ pub postal_code: Secret<String>,
+ pub country_code: common_enums::CountryAlpha2,
}
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsRequest {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub channel: Option<Channel>,
+ pub transaction_reference: String,
+ pub merchant: Merchant,
pub instruction: Instruction,
+ pub channel: Channel,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Customer>,
- pub merchant: Merchant,
- pub transaction_reference: String,
}
#[derive(
@@ -35,6 +34,7 @@ pub struct WorldpayPaymentsRequest {
#[serde(rename_all = "camelCase")]
pub enum Channel {
#[default]
+ Ecom,
Moto,
}
@@ -101,11 +101,18 @@ pub struct NetworkToken {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub debt_repayment: Option<bool>,
- pub value: PaymentValue,
+ pub request_auto_settlement: RequestAutoSettlement,
pub narrative: InstructionNarrative,
+ pub value: PaymentValue,
pub payment_instrument: PaymentInstrument,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub debt_repayment: Option<bool>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RequestAutoSettlement {
+ pub enabled: bool,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
@@ -143,16 +150,15 @@ pub enum PaymentType {
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardPayment {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub billing_address: Option<BillingAddress>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub card_holder_name: Option<Secret<String>>,
- pub card_expiry_date: CardExpiryDate,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub cvc: Option<Secret<String>>,
#[serde(rename = "type")]
pub payment_type: PaymentType,
pub card_number: cards::CardNumber,
+ pub expiry_date: ExpiryDate,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub card_holder_name: Option<Secret<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub billing_address: Option<BillingAddress>,
+ pub cvc: Secret<String>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
@@ -174,7 +180,7 @@ pub struct WalletPayment {
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-pub struct CardExpiryDate {
+pub struct ExpiryDate {
pub month: Secret<i8>,
pub year: Secret<i32>,
}
@@ -182,13 +188,13 @@ pub struct CardExpiryDate {
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PaymentValue {
pub amount: i64,
- pub currency: String,
+ pub currency: api_models::enums::Currency,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
- pub entity: String,
+ pub entity: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -220,7 +226,7 @@ pub struct SubMerchant {
}
#[derive(Default, Debug, Serialize)]
-pub struct WorldpayRefundRequest {
+pub struct WorldpayPartialRequest {
pub value: PaymentValue,
pub reference: String,
}
diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs
index 14ccbc1fac8..dbd596e2e20 100644
--- a/crates/router/src/connector/worldpay/response.rs
+++ b/crates/router/src/connector/worldpay/response.rs
@@ -1,33 +1,43 @@
use masking::Secret;
use serde::{Deserialize, Serialize};
+use super::requests::*;
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayPaymentsResponse {
+ pub outcome: Option<PaymentOutcome>,
+ /// Any risk factors which have been identified for the authorization. This section will not appear if no risks are identified.
#[serde(skip_serializing_if = "Option::is_none")]
- pub exemption: Option<Exemption>,
+ pub risk_factors: Option<Vec<RiskFactorsInner>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub issuer: Option<Issuer>,
- pub outcome: Option<Outcome>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub description: Option<String>,
+ pub scheme: Option<PaymentsResponseScheme>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_instrument: Option<PaymentsResPaymentInstrument>,
- /// Any risk factors which have been identified for the authorization. This section will not appear if no risks are identified.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub risk_factors: Option<Vec<RiskFactorsInner>>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub scheme: Option<PaymentsResponseScheme>,
#[serde(rename = "_links", skip_serializing_if = "Option::is_none")]
pub links: Option<PaymentLinks>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub description: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
-pub enum Outcome {
+pub enum PaymentOutcome {
+ #[serde(alias = "authorized", alias = "Authorized")]
Authorized,
Refused,
+ #[serde(alias = "Sent for Settlement")]
+ SentForSettlement,
+ #[serde(alias = "Sent for Refund")]
+ SentForRefund,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub enum RefundOutcome {
+ #[serde(alias = "Sent for Refund")]
+ SentForRefund,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -41,31 +51,57 @@ pub struct WorldpayEventResponse {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum EventType {
+ SentForAuthorization,
+ #[serde(alias = "Authorized")]
Authorized,
+ #[serde(alias = "Sent for Settlement")]
+ SentForSettlement,
+ Settled,
+ SettlementFailed,
Cancelled,
- Charged,
- SentForRefund,
- RefundFailed,
- Refused,
- Refunded,
Error,
- SentForSettlement,
Expired,
- CaptureFailed,
+ Refused,
+ #[serde(alias = "Sent for Refund")]
+ SentForRefund,
+ Refunded,
+ RefundFailed,
#[serde(other)]
Unknown,
}
-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-pub struct Exemption {
- pub result: String,
- pub reason: String,
-}
-
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PaymentLinks {
- #[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")]
+ #[serde(
+ rename = "cardPayments:events",
+ skip_serializing_if = "Option::is_none"
+ )]
pub events: Option<PaymentLink>,
+ #[serde(
+ rename = "cardPayments:settle",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub settle_event: Option<PaymentLink>,
+ #[serde(
+ rename = "cardPayments:partialSettle",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub partial_settle_event: Option<PaymentLink>,
+ #[serde(
+ rename = "cardPayments:refund",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub refund_event: Option<PaymentLink>,
+ #[serde(
+ rename = "cardPayments:partialRefund",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub partial_refund_event: Option<PaymentLink>,
+ #[serde(
+ rename = "cardPayments:reverse",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub reverse_event: Option<PaymentLink>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
@@ -116,12 +152,6 @@ impl ForeignTryFrom<Option<PaymentLinks>> for types::ResponseId {
}
}
-impl Exemption {
- pub fn new(result: String, reason: String) -> Self {
- Self { result, reason }
- }
-}
-
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Issuer {
@@ -137,103 +167,32 @@ impl Issuer {
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct PaymentsResPaymentInstrument {
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
- pub risk_type: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub card: Option<PaymentInstrumentCard>,
-}
-
-impl PaymentsResPaymentInstrument {
- pub fn new() -> Self {
- Self {
- risk_type: None,
- card: None,
- }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInstrumentCard {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub number: Option<PaymentInstrumentCardNumber>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub issuer: Option<PaymentInstrumentCardIssuer>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub payment_account_reference: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub country_code: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
+ pub payment_instrument_type: Option<String>,
+ pub card_bin: Option<String>,
+ pub last_four: Option<String>,
+ pub category: Option<String>,
+ pub expiry_date: Option<ExpiryDate>,
+ pub card_brand: Option<String>,
pub funding_type: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub brand: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub expiry_date: Option<PaymentInstrumentCardExpiryDate>,
+ pub issuer_name: Option<String>,
+ pub payment_account_reference: Option<String>,
}
-impl PaymentInstrumentCard {
+impl PaymentsResPaymentInstrument {
pub fn new() -> Self {
Self {
- number: None,
- issuer: None,
- payment_account_reference: None,
- country_code: None,
- funding_type: None,
- brand: None,
+ payment_instrument_type: None,
+ card_bin: None,
+ last_four: None,
+ category: None,
expiry_date: None,
- }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInstrumentCardExpiryDate {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub month: Option<Secret<i32>>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub year: Option<Secret<i32>>,
-}
-
-impl PaymentInstrumentCardExpiryDate {
- pub fn new() -> Self {
- Self {
- month: None,
- year: None,
- }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInstrumentCardIssuer {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub name: Option<String>,
-}
-
-impl PaymentInstrumentCardIssuer {
- pub fn new() -> Self {
- Self { name: None }
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInstrumentCardNumber {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub bin: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub last4_digits: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub dpan: Option<String>,
-}
-
-impl PaymentInstrumentCardNumber {
- pub fn new() -> Self {
- Self {
- bin: None,
- last4_digits: None,
- dpan: None,
+ card_brand: None,
+ funding_type: None,
+ issuer_name: None,
+ payment_account_reference: None,
}
}
}
@@ -282,15 +241,12 @@ pub enum Detail {
#[derive(
Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize,
)]
+#[serde(rename_all = "camelCase")]
pub enum Risk {
#[default]
- #[serde(rename = "not_checked")]
NotChecked,
- #[serde(rename = "not_matched")]
NotMatched,
- #[serde(rename = "not_supplied")]
NotSupplied,
- #[serde(rename = "verificationFailed")]
VerificationFailed,
}
@@ -305,7 +261,7 @@ impl PaymentsResponseScheme {
}
}
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayErrorResponse {
pub error_name: String,
@@ -313,6 +269,23 @@ pub struct WorldpayErrorResponse {
pub validation_errors: Option<serde_json::Value>,
}
+impl WorldpayErrorResponse {
+ pub fn default(status_code: u16) -> Self {
+ match status_code {
+ code @ 404 => Self {
+ error_name: format!("{} Not found", code),
+ message: "Resource not found".to_string(),
+ validation_errors: None,
+ },
+ code => Self {
+ error_name: code.to_string(),
+ message: "Unknown error".to_string(),
+ validation_errors: None,
+ },
+ }
+ }
+}
+
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorldpayWebhookTransactionId {
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index dca6f82adc1..c5398b83a86 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -1,6 +1,9 @@
+use api_models::payments::Address;
use base64::Engine;
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, ext_traits::OptionExt, types::MinorUnit};
use diesel_models::enums;
+use error_stack::ResultExt;
+use hyperswitch_connectors::utils::RouterData;
use masking::{PeekInterface, Secret};
use serde::Serialize;
@@ -23,36 +26,61 @@ impl<T>
TryFrom<(
&types::api::CurrencyUnit,
types::storage::enums::Currency,
- i64,
+ MinorUnit,
T,
)> for WorldpayRouterData<T>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (_currency_unit, _currency, amount, item): (
+ (_currency_unit, _currency, minor_amount, item): (
&types::api::CurrencyUnit,
types::storage::enums::Currency,
- i64,
+ MinorUnit,
T,
),
) -> Result<Self, Self::Error> {
Ok(Self {
- amount,
+ amount: minor_amount.get_amount_as_i64(),
router_data: item,
})
}
}
fn fetch_payment_instrument(
payment_method: domain::PaymentMethodData,
+ billing_address: Option<&Address>,
) -> CustomResult<PaymentInstrument, errors::ConnectorError> {
match payment_method {
domain::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment {
- card_expiry_date: CardExpiryDate {
+ payment_type: PaymentType::Card,
+ expiry_date: ExpiryDate {
month: utils::CardData::get_expiry_month_as_i8(&card)?,
year: utils::CardData::get_expiry_year_as_i32(&card)?,
},
card_number: card.card_number,
- ..CardPayment::default()
+ cvc: card.card_cvc,
+ card_holder_name: card.nick_name,
+ billing_address: if let Some(address) =
+ billing_address.and_then(|addr| addr.address.clone())
+ {
+ Some(BillingAddress {
+ address1: address.line1,
+ address2: address.line2,
+ address3: address.line3,
+ city: address.city,
+ state: address.state,
+ postal_code: address.zip.get_required_value("zip").change_context(
+ errors::ConnectorError::MissingRequiredField { field_name: "zip" },
+ )?,
+ country_code: address
+ .country
+ .get_required_value("country_code")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "country_code",
+ })?,
+ })
+ } else {
+ None
+ },
})),
domain::PaymentMethodData::Wallet(wallet) => match wallet {
domain::WalletData::GooglePay(data) => {
@@ -122,7 +150,7 @@ fn fetch_payment_instrument(
}
impl
- TryFrom<
+ TryFrom<(
&WorldpayRouterData<
&types::RouterData<
types::api::payments::Authorize,
@@ -130,24 +158,33 @@ impl
PaymentsResponseData,
>,
>,
- > for WorldpayPaymentsRequest
+ &Secret<String>,
+ )> for WorldpayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &WorldpayRouterData<
- &types::RouterData<
- types::api::payments::Authorize,
- PaymentsAuthorizeData,
- PaymentsResponseData,
+ req: (
+ &WorldpayRouterData<
+ &types::RouterData<
+ types::api::payments::Authorize,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
>,
- >,
+ &Secret<String>,
+ ),
) -> Result<Self, Self::Error> {
+ let (item, entity_id) = req;
Ok(Self {
instruction: Instruction {
+ request_auto_settlement: RequestAutoSettlement {
+ enabled: item.router_data.request.capture_method
+ == Some(enums::CaptureMethod::Automatic),
+ },
value: PaymentValue {
amount: item.amount,
- currency: item.router_data.request.currency.to_string(),
+ currency: item.router_data.request.currency,
},
narrative: InstructionNarrative {
line1: item
@@ -159,19 +196,16 @@ impl
},
payment_instrument: fetch_payment_instrument(
item.router_data.request.payment_method_data.clone(),
+ item.router_data.get_optional_billing(),
)?,
debt_repayment: None,
},
merchant: Merchant {
- entity: item
- .router_data
- .connector_request_reference_id
- .clone()
- .replace('_', "-"),
+ entity: entity_id.clone(),
..Default::default()
},
transaction_reference: item.router_data.connector_request_reference_id.clone(),
- channel: None,
+ channel: Channel::Ecom,
customer: None,
})
}
@@ -179,17 +213,32 @@ impl
pub struct WorldpayAuthType {
pub(super) api_key: Secret<String>,
+ pub(super) entity_id: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
+ // TODO: Remove this later, kept purely for backwards compatibility
types::ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
+ entity_id: Secret::new("default".to_string()),
+ })
+ }
+ types::ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => {
+ let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
+ let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
+ Ok(Self {
+ api_key: Secret::new(auth_header),
+ entity_id: api_secret.clone(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
@@ -197,22 +246,25 @@ impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType {
}
}
-impl From<Outcome> for enums::AttemptStatus {
- fn from(item: Outcome) -> Self {
+impl From<PaymentOutcome> for enums::AttemptStatus {
+ fn from(item: PaymentOutcome) -> Self {
match item {
- Outcome::Authorized => Self::Authorized,
- Outcome::Refused => Self::Failure,
+ PaymentOutcome::Authorized => Self::Authorized,
+ PaymentOutcome::Refused => Self::Failure,
+ PaymentOutcome::SentForSettlement => Self::CaptureInitiated,
+ PaymentOutcome::SentForRefund => Self::AutoRefunded,
}
}
}
-impl From<EventType> for enums::AttemptStatus {
- fn from(value: EventType) -> Self {
+impl From<&EventType> for enums::AttemptStatus {
+ fn from(value: &EventType) -> Self {
match value {
+ EventType::SentForAuthorization => Self::Authorizing,
+ EventType::SentForSettlement => Self::CaptureInitiated,
+ EventType::Settled => Self::Charged,
EventType::Authorized => Self::Authorized,
- EventType::CaptureFailed => Self::CaptureFailed,
- EventType::Refused => Self::Failure,
- EventType::Charged | EventType::SentForSettlement => Self::Charged,
+ EventType::Refused | EventType::SettlementFailed => Self::Failure,
EventType::Cancelled
| EventType::SentForRefund
| EventType::RefundFailed
@@ -227,17 +279,17 @@ impl From<EventType> for enums::AttemptStatus {
impl From<EventType> for enums::RefundStatus {
fn from(value: EventType) -> Self {
match value {
- EventType::Refunded => Self::Success,
+ EventType::Refunded | EventType::SentForRefund => Self::Success,
EventType::RefundFailed => Self::Failure,
EventType::Authorized
| EventType::Cancelled
- | EventType::Charged
- | EventType::SentForRefund
+ | EventType::Settled
| EventType::Refused
| EventType::Error
| EventType::SentForSettlement
+ | EventType::SentForAuthorization
+ | EventType::SettlementFailed
| EventType::Expired
- | EventType::CaptureFailed
| EventType::Unknown => Self::Pending,
}
}
@@ -273,14 +325,29 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>>
}
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldpayRefundRequest {
+impl TryFrom<(&types::PaymentsCaptureRouterData, MinorUnit)> for WorldpayPartialRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(req: (&types::PaymentsCaptureRouterData, MinorUnit)) -> Result<Self, Self::Error> {
+ let (item, amount) = req;
+ Ok(Self {
+ reference: item.payment_id.clone().replace("_", "-"),
+ value: PaymentValue {
+ amount: amount.get_amount_as_i64(),
+ currency: item.request.currency,
+ },
+ })
+ }
+}
+
+impl<F> TryFrom<(&types::RefundsRouterData<F>, MinorUnit)> for WorldpayPartialRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(req: (&types::RefundsRouterData<F>, MinorUnit)) -> Result<Self, Self::Error> {
+ let (item, amount) = req;
Ok(Self {
- reference: item.request.connector_transaction_id.clone(),
+ reference: item.request.refund_id.clone().replace("_", "-"),
value: PaymentValue {
- amount: item.request.refund_amount,
- currency: item.request.currency.to_string(),
+ amount: amount.get_amount_as_i64(),
+ currency: item.request.currency,
},
})
}
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index 6b25be73185..68db6423e06 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -106,7 +106,10 @@ impl
payment_method,
error_code: self.payment_attempt.error_code.clone(),
error_message: self.payment_attempt.error_message.clone(),
- connector_transaction_id: self.payment_attempt.connector_transaction_id.clone(),
+ connector_transaction_id: self
+ .payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string),
connector: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 2257c42f446..0ea78e1ce14 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -6,7 +6,7 @@ use async_trait::async_trait;
use common_enums::{AuthorizationStatus, SessionUpdateStatus};
use common_utils::{
ext_traits::{AsyncExt, Encode},
- types::{keymanager::KeyManagerState, MinorUnit},
+ types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},
};
use error_stack::{report, ResultExt};
use futures::FutureExt;
@@ -1400,6 +1400,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
} => {
let connector_transaction_id = match pre_processing_id.to_owned() {
types::PreprocessingResponseId::PreProcessingId(_) => None,
+
types::PreprocessingResponseId::ConnectorTransactionId(
connector_txn_id,
) => Some(connector_txn_id),
@@ -1446,8 +1447,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
);
let connector_transaction_id = match resource_id {
types::ResponseId::NoResponseId => None,
- types::ResponseId::ConnectorTransactionId(id)
- | types::ResponseId::EncodedData(id) => Some(id),
+ types::ResponseId::ConnectorTransactionId(ref id)
+ | types::ResponseId::EncodedData(ref id) => Some(id),
};
let encoded_data = payment_data.payment_attempt.encoded_data.clone();
@@ -1496,12 +1497,23 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.multiple_capture_data
{
Some(multiple_capture_data) => {
+ let (connector_capture_id, connector_capture_data) =
+ match resource_id {
+ types::ResponseId::NoResponseId => (None, None),
+ types::ResponseId::ConnectorTransactionId(id)
+ | types::ResponseId::EncodedData(id) => {
+ let (txn_id, txn_data) =
+ ConnectorTransactionId::form_id_and_data(id);
+ (Some(txn_id), txn_data)
+ }
+ };
let capture_update = storage::CaptureUpdate::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(
router_data.status,
)?,
- connector_capture_id: connector_transaction_id.clone(),
+ connector_capture_id: connector_capture_id.clone(),
connector_response_reference_id,
+ connector_capture_data: connector_capture_data.clone(),
};
let capture_update_list = vec![(
multiple_capture_data.get_latest_capture().clone(),
@@ -1519,7 +1531,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
Some(storage::PaymentAttemptUpdate::ResponseUpdate {
status: updated_attempt_status,
connector: None,
- connector_transaction_id: connector_transaction_id.clone(),
+ connector_transaction_id: connector_transaction_id.cloned(),
authentication_type: auth_update,
amount_capturable: router_data
.request
@@ -1872,7 +1884,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
&add_attributes([
(
"connector",
- payment_data.payment_attempt.connector.unwrap_or_default(),
+ payment_data
+ .payment_attempt
+ .connector
+ .clone()
+ .unwrap_or_default(),
),
(
"merchant_id",
@@ -1886,12 +1902,15 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
);
Err(error_stack::Report::new(
errors::ApiErrorResponse::IntegrityCheckFailed {
+ connector_transaction_id: payment_data
+ .payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string),
reason: payment_data
.payment_attempt
.error_message
.unwrap_or_default(),
field_names: err.field_names,
- connector_transaction_id: payment_data.payment_attempt.connector_transaction_id,
},
))
}
@@ -2015,7 +2034,7 @@ fn response_to_capture_update(
let mut unmapped_captures = vec![];
for (connector_capture_id, capture_sync_response) in response_list {
let capture =
- multiple_capture_data.get_capture_by_connector_capture_id(connector_capture_id);
+ multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id);
if let Some(capture) = capture {
capture_update_list.push((
capture.clone(),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 72e6c6b9979..8ad39ffc894 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -9,7 +9,7 @@ use common_utils::{
consts::X_HS_LATENCY,
fp_utils,
pii::Email,
- types::{AmountConvertor, MinorUnit, StringMajorUnitForConnector},
+ types::{self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnitForConnector},
};
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
@@ -204,8 +204,8 @@ where
let resource_id = match payment_data
.payment_attempt
- .connector_transaction_id
- .clone()
+ .get_connector_payment_id()
+ .map(ToString::to_string)
{
Some(id) => types::ResponseId::ConnectorTransactionId(id),
None => types::ResponseId::NoResponseId,
@@ -1163,6 +1163,10 @@ where
})
});
+ let connector_transaction_id = payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string);
+
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
merchant_id: payment_intent.merchant_id,
@@ -1231,7 +1235,7 @@ where
connector_request_reference_id_config,
&merchant_id,
),
- connector_transaction_id: payment_attempt.connector_transaction_id,
+ connector_transaction_id,
frm_message,
metadata: payment_intent.metadata,
connector_metadata: payment_intent.connector_metadata,
@@ -1396,6 +1400,7 @@ pub fn wait_screen_next_steps_check(
#[cfg(feature = "v1")]
impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse {
fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self {
+ let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string);
Self {
payment_id: pi.payment_id,
merchant_id: pi.merchant_id,
@@ -1418,7 +1423,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
setup_future_usage: pi.setup_future_usage,
capture_method: pa.capture_method,
authentication_type: pa.authentication_type,
- connector_transaction_id: pa.connector_transaction_id,
+ connector_transaction_id,
attempt_count: pi.attempt_count,
profile_id: pi.profile_id,
merchant_connector_id: pa.merchant_connector_id,
@@ -1983,6 +1988,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureD
})?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
+ capture_method: payment_data.get_capture_method(),
amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module
minor_amount_to_capture: amount_to_capture,
currency: payment_data.currency,
@@ -2321,14 +2327,21 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate {
connector_response_reference_id,
..
} => {
- let connector_capture_id = match resource_id {
- types::ResponseId::ConnectorTransactionId(id) => Some(id),
- types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => None,
+ let (connector_capture_id, connector_capture_data) = match resource_id {
+ types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => {
+ (None, None)
+ }
+ types::ResponseId::ConnectorTransactionId(id) => {
+ let (txn_id, txn_data) =
+ common_utils_type::ConnectorTransactionId::form_id_and_data(id);
+ (Some(txn_id), txn_data)
+ }
};
Ok(Self::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(status)?,
connector_capture_id,
connector_response_reference_id,
+ connector_capture_data,
})
}
types::CaptureSyncResponse::Error {
@@ -2395,7 +2408,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz
browser_info,
email: payment_data.email,
payment_method_data: payment_data.payment_method_data.map(From::from),
- connector_transaction_id: payment_data.payment_attempt.connector_transaction_id,
+ connector_transaction_id: payment_data
+ .payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string),
redirect_response,
connector_meta: payment_data.payment_attempt.connector_metadata,
complete_authorize_url,
@@ -2494,7 +2510,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce
complete_authorize_url,
browser_info,
surcharge_details: payment_data.surcharge_details,
- connector_transaction_id: payment_data.payment_attempt.connector_transaction_id,
+ connector_transaction_id: payment_data
+ .payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string),
redirect_response: None,
mandate_id: payment_data.mandate_id,
related_transaction_id: None,
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 3034b74db45..1a7e2047678 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -4,7 +4,7 @@ use api_models::payment_methods::SurchargeDetailsResponse;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt},
- types as common_types,
+ types::{self as common_types, ConnectorTransactionIdTrait},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
@@ -162,11 +162,13 @@ impl MultipleCaptureData {
}
pub fn get_capture_by_connector_capture_id(
&self,
- connector_capture_id: String,
+ connector_capture_id: &String,
) -> Option<&storage::Capture> {
self.all_captures
.iter()
- .find(|(_, capture)| capture.connector_capture_id == Some(connector_capture_id.clone()))
+ .find(|(_, capture)| {
+ capture.get_optional_connector_transaction_id() == Some(connector_capture_id)
+ })
.map(|(_, capture)| capture)
}
pub fn get_latest_capture(&self) -> &storage::Capture {
@@ -176,14 +178,14 @@ impl MultipleCaptureData {
let pending_connector_capture_ids = self
.get_pending_captures()
.into_iter()
- .filter_map(|capture| capture.connector_capture_id.clone())
+ .filter_map(|capture| capture.get_optional_connector_transaction_id().cloned())
.collect();
pending_connector_capture_ids
}
pub fn get_pending_captures_without_connector_capture_id(&self) -> Vec<&storage::Capture> {
self.get_pending_captures()
.into_iter()
- .filter(|capture| capture.connector_capture_id.is_none())
+ .filter(|capture| capture.get_optional_connector_transaction_id().is_none())
.collect()
}
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index cf0374fe826..86211770e0d 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -8,7 +8,7 @@ use std::collections::HashMap;
use api_models::admin::MerchantConnectorInfo;
use common_utils::{
ext_traits::{AsyncExt, ValueExt},
- types::MinorUnit,
+ types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
@@ -235,6 +235,7 @@ pub async fn trigger_refund_to_gateway(
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
+ connector_refund_data: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
@@ -246,6 +247,7 @@ pub async fn trigger_refund_to_gateway(
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
+ connector_refund_data: None,
})
}
_ => None,
@@ -287,12 +289,18 @@ pub async fn trigger_refund_to_gateway(
refund_error_code: Some(err.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
+ connector_refund_data: None,
},
Ok(response) => {
// match on connector integrity checks
match router_data_res.integrity_check.clone() {
Err(err) => {
- let refund_connector_transaction_id = err.connector_transaction_id;
+ let (refund_connector_transaction_id, connector_refund_data) =
+ err.connector_transaction_id.map_or((None, None), |txn_id| {
+ let (refund_id, refund_data) =
+ ConnectorTransactionId::form_id_and_data(txn_id);
+ (Some(refund_id), refund_data)
+ });
metrics::INTEGRITY_CHECK_FAILED.add(
&metrics::CONTEXT,
1,
@@ -313,6 +321,7 @@ pub async fn trigger_refund_to_gateway(
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
+ connector_refund_data,
}
}
Ok(()) => {
@@ -323,13 +332,16 @@ pub async fn trigger_refund_to_gateway(
&add_attributes([("connector", connector.connector_name.to_string())]),
)
}
+ let (connector_refund_id, connector_refund_data) =
+ ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
storage::RefundUpdate::Update {
- connector_refund_id: response.connector_refund_id,
+ connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
+ connector_refund_data,
}
}
}
@@ -424,7 +436,7 @@ pub async fn refund_retrieve_core(
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &refund.connector_transaction_id,
+ refund.get_connector_transaction_id(),
payment_id,
merchant_id,
merchant_account.storage_scheme,
@@ -591,6 +603,7 @@ pub async fn sync_refund_with_gateway(
refund_error_code: Some(error_message.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
+ connector_refund_data: None,
}
}
Ok(response) => match router_data_res.integrity_check.clone() {
@@ -606,7 +619,13 @@ pub async fn sync_refund_with_gateway(
),
]),
);
- let refund_connector_transaction_id = err.connector_transaction_id;
+ let (refund_connector_transaction_id, connector_refund_data) = err
+ .connector_transaction_id
+ .map_or((None, None), |refund_id| {
+ let (refund_id, refund_data) =
+ ConnectorTransactionId::form_id_and_data(refund_id);
+ (Some(refund_id), refund_data)
+ });
storage::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
@@ -616,16 +635,22 @@ pub async fn sync_refund_with_gateway(
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
+ connector_refund_data,
+ }
+ }
+ Ok(()) => {
+ let (connector_refund_id, connector_refund_data) =
+ ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
+ storage::RefundUpdate::Update {
+ connector_refund_id,
+ refund_status: response.refund_status,
+ sent_to_gateway: true,
+ refund_error_message: None,
+ refund_arn: "".to_string(),
+ updated_by: storage_scheme.to_string(),
+ connector_refund_data,
}
}
- Ok(()) => storage::RefundUpdate::Update {
- connector_refund_id: response.connector_refund_id,
- refund_status: response.refund_status,
- sent_to_gateway: true,
- refund_error_message: None,
- refund_arn: "".to_string(),
- updated_by: storage_scheme.to_string(),
- },
},
};
@@ -752,7 +777,7 @@ pub async fn validate_and_create_refund(
.attach_printable("invalid merchant_id in request"))
})?;
- let connecter_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| {
+ let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
@@ -760,7 +785,7 @@ pub async fn validate_and_create_refund(
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_account.get_id(),
- &connecter_transaction_id,
+ &connector_transaction_id,
merchant_account.storage_scheme,
)
.await
@@ -800,13 +825,15 @@ pub async fn validate_and_create_refund(
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
+ let (connector_transaction_id, connector_transaction_data) =
+ ConnectorTransactionId::form_id_and_data(connector_transaction_id);
let refund_create_req = storage::RefundNew {
refund_id: refund_id.to_string(),
internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
external_reference_id: Some(refund_id.clone()),
payment_id: req.payment_id,
merchant_id: merchant_account.get_id().clone(),
- connector_transaction_id: connecter_transaction_id.to_string(),
+ connector_transaction_id,
connector,
refund_type: req.refund_type.unwrap_or_default().foreign_into(),
total_amount: payment_attempt.get_total_amount(),
@@ -827,6 +854,8 @@ pub async fn validate_and_create_refund(
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_account.organization_id.clone(),
+ connector_refund_data: None,
+ connector_transaction_data,
};
let refund = match db
@@ -1402,7 +1431,7 @@ pub async fn trigger_refund_execute_workflow(
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
- &refund.connector_transaction_id,
+ refund.get_connector_transaction_id(),
&refund_core.payment_id,
&refund.merchant_id,
merchant_account.storage_scheme,
@@ -1506,6 +1535,7 @@ pub fn refund_to_refund_core_workflow_model(
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
+ connector_transaction_data: refund.connector_transaction_data.clone(),
}
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index ae8b7c15a73..a6a9c36bfda 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -12,7 +12,7 @@ use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{
errors::CustomResult,
ext_traits::AsyncExt,
- types::{keymanager::KeyManagerState, MinorUnit},
+ types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
@@ -325,6 +325,8 @@ pub async fn construct_refund_router_data<'a, F>(
field_name: "browser_info",
})?;
+ let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
+
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.get_id().clone(),
@@ -349,7 +351,7 @@ pub async fn construct_refund_router_data<'a, F>(
minor_amount_captured: payment_intent.amount_captured,
request: types::RefundsData {
refund_id: refund.refund_id.clone(),
- connector_transaction_id: refund.connector_transaction_id.clone(),
+ connector_transaction_id: refund.get_connector_transaction_id().clone(),
refund_amount: refund.refund_amount.get_amount_as_i64(),
minor_refund_amount: refund.refund_amount,
currency,
@@ -358,14 +360,14 @@ pub async fn construct_refund_router_data<'a, F>(
webhook_url,
connector_metadata: payment_attempt.connector_metadata.clone(),
reason: refund.refund_reason.clone(),
- connector_refund_id: refund.connector_refund_id.clone(),
+ connector_refund_id: connector_refund_id.clone(),
browser_info,
charges,
integrity_object: None,
},
response: Ok(types::RefundsResponseData {
- connector_refund_id: refund.connector_refund_id.clone().unwrap_or_default(),
+ connector_refund_id: connector_refund_id.unwrap_or_default(),
refund_status: refund.refund_status,
}),
access_token: None,
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index af531984a19..3942c395665 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -814,6 +814,7 @@ async fn refunds_incoming_webhook_flow(
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("failed refund status mapping from event type")?,
updated_by: merchant_account.storage_scheme.to_string(),
+ connector_refund_data: None,
};
db.update_refund(
refund.to_owned(),
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 335110248ab..3a8750feff9 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -391,11 +391,11 @@ mod storage {
let field = format!("add_{}", address_id);
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Address>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -502,14 +502,14 @@ mod storage {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<storage_types::Address>(
(&field, redis_value),
redis_entry,
),
key,
- )
+ ))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hset()
@@ -601,7 +601,7 @@ mod storage {
},
};
- match kv_wrapper::<diesel_models::Address, _, _>(
+ match Box::pin(kv_wrapper::<diesel_models::Address, _, _>(
self,
KvOperation::HSetNx::<diesel_models::Address>(
&field,
@@ -609,7 +609,7 @@ mod storage {
redis_entry,
),
key,
- )
+ ))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hsetnx()
diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs
index 16b18a873d3..cbc27f918d4 100644
--- a/crates/router/src/db/capture.rs
+++ b/crates/router/src/db/capture.rs
@@ -198,6 +198,7 @@ impl CaptureInterface for MockDb {
capture_sequence: capture.capture_sequence,
connector_capture_id: capture.connector_capture_id,
connector_response_reference_id: capture.connector_response_reference_id,
+ connector_capture_data: capture.connector_capture_data,
};
captures.push(capture.clone());
Ok(capture)
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 9cd044f69eb..5020c238e4a 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -219,11 +219,11 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
// check for ValueNotFound
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Customer>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
.map(Some)
@@ -293,11 +293,11 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
// check for ValueNotFound
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Customer>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
.map(Some)
@@ -453,14 +453,14 @@ mod storage {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<diesel_models::Customer>(
(&field, redis_value),
redis_entry,
),
key,
- )
+ ))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hset()
@@ -584,11 +584,11 @@ mod storage {
let field = format!("cust_{}", customer_id.get_string_repr());
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Customer>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -773,7 +773,7 @@ mod storage {
};
let storage_customer = new_customer.into();
- match kv_wrapper::<diesel_models::Customer, _, _>(
+ match Box::pin(kv_wrapper::<diesel_models::Customer, _, _>(
self,
KvOperation::HSetNx::<diesel_models::Customer>(
&field,
@@ -781,7 +781,7 @@ mod storage {
redis_entry,
),
key,
- )
+ ))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hsetnx()
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index 40e5f88614d..95733805b43 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -114,11 +114,11 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Mandate>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -172,11 +172,11 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -281,14 +281,14 @@ mod storage {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<diesel_models::Mandate>::Hset(
(&field, redis_value),
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -369,7 +369,7 @@ mod storage {
.await?;
}
- match kv_wrapper::<diesel_models::Mandate, _, _>(
+ match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>(
self,
KvOperation::<diesel_models::Mandate>::HSetNx(
&field,
@@ -377,7 +377,7 @@ mod storage {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 6e052076799..e75fb940a35 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -210,13 +210,13 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::PaymentMethod>::HGet(
&lookup.sk_id,
),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -348,13 +348,13 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::PaymentMethod>::HGet(
&lookup.sk_id,
),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -500,7 +500,7 @@ mod storage {
},
};
- match kv_wrapper::<diesel_models::PaymentMethod, _, _>(
+ match Box::pin(kv_wrapper::<diesel_models::PaymentMethod, _, _>(
self,
KvOperation::<diesel_models::PaymentMethod>::HSetNx(
&field,
@@ -508,7 +508,7 @@ mod storage {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -597,14 +597,14 @@ mod storage {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<diesel_models::PaymentMethod>::Hset(
(&field, redis_value),
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -743,11 +743,11 @@ mod storage {
let pattern = "payment_method_id_*";
let redis_fut = async {
- let kv_result = kv_wrapper::<storage_types::PaymentMethod, _, _>(
+ let kv_result = Box::pin(kv_wrapper::<storage_types::PaymentMethod, _, _>(
self,
KvOperation::<storage_types::PaymentMethod>::Scan(pattern),
key,
- )
+ ))
.await?
.try_into_scan();
kv_result.map(|payment_methods| {
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index cf092ad410e..41cb3cef5c6 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
#[cfg(feature = "olap")]
-use common_utils::types::MinorUnit;
+use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit};
use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal};
use hyperswitch_domain_models::refunds;
@@ -298,7 +298,9 @@ mod storage {
#[cfg(feature = "kv_store")]
mod storage {
- use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found};
+ use common_utils::{
+ ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait,
+ };
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::refunds;
use redis_interface::HsetnxReply;
@@ -359,11 +361,11 @@ mod storage {
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -432,6 +434,8 @@ mod storage {
merchant_connector_id: new.merchant_connector_id.clone(),
charges: new.charges.clone(),
organization_id: new.organization_id.clone(),
+ connector_refund_data: new.connector_refund_data.clone(),
+ connector_transaction_data: new.connector_transaction_data.clone(),
};
let field = format!(
@@ -470,7 +474,8 @@ mod storage {
updated_by: storage_scheme.to_string(),
},
];
- if let Some(connector_refund_id) = created_refund.to_owned().connector_refund_id
+ if let Some(connector_refund_id) =
+ created_refund.to_owned().get_optional_connector_refund_id()
{
reverse_lookups.push(storage_types::ReverseLookupNew {
sk_id: field.clone(),
@@ -491,7 +496,7 @@ mod storage {
futures::future::try_join_all(rev_look).await?;
- match kv_wrapper::<storage_types::Refund, _, _>(
+ match Box::pin(kv_wrapper::<storage_types::Refund, _, _>(
self,
KvOperation::<storage_types::Refund>::HSetNx(
&field,
@@ -499,7 +504,7 @@ mod storage {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -560,11 +565,11 @@ mod storage {
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::Refund>::Scan(&pattern),
key,
- )
+ ))
.await?
.try_into_scan()
},
@@ -619,14 +624,14 @@ mod storage {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<storage_types::Refund>(
(&field, redis_value),
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -672,11 +677,11 @@ mod storage {
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -730,11 +735,11 @@ mod storage {
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -777,11 +782,11 @@ mod storage {
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<storage_types::Refund>::Scan("pa_*_ref_*"),
key,
- )
+ ))
.await?
.try_into_scan()
},
@@ -921,6 +926,8 @@ impl RefundInterface for MockDb {
merchant_connector_id: new.merchant_connector_id,
charges: new.charges,
organization_id: new.organization_id,
+ connector_refund_data: new.connector_refund_data,
+ connector_transaction_data: new.connector_transaction_data,
};
refunds.push(refund.clone());
Ok(refund)
@@ -937,7 +944,7 @@ impl RefundInterface for MockDb {
.iter()
.take_while(|refund| {
refund.merchant_id == *merchant_id
- && refund.connector_transaction_id == connector_transaction_id
+ && refund.get_connector_transaction_id() == connector_transaction_id
})
.cloned()
.collect::<Vec<_>>())
@@ -995,7 +1002,10 @@ impl RefundInterface for MockDb {
.iter()
.find(|refund| {
refund.merchant_id == *merchant_id
- && refund.connector_refund_id == Some(connector_refund_id.to_string())
+ && refund
+ .get_optional_connector_refund_id()
+ .map(|refund_id| refund_id.as_str())
+ == Some(connector_refund_id)
&& refund.connector == connector
})
.cloned()
diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs
index d51ed5ed385..06bd84675b1 100644
--- a/crates/router/src/db/reverse_lookup.rs
+++ b/crates/router/src/db/reverse_lookup.rs
@@ -120,7 +120,7 @@ mod storage {
},
};
- match kv_wrapper::<ReverseLookup, _, _>(
+ match Box::pin(kv_wrapper::<ReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
@@ -129,7 +129,7 @@ mod storage {
&created_rev_lookup.lookup_id
),
},
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
@@ -168,13 +168,13 @@ mod storage {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<ReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
- )
+ ))
.await?
.try_into_get()
};
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index c4fb4a43dd0..7eff6f881ba 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -1,4 +1,7 @@
-use common_utils::{id_type, types::MinorUnit};
+use common_utils::{
+ id_type,
+ types::{ConnectorTransactionIdTrait, MinorUnit},
+};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -39,9 +42,9 @@ impl<'a> KafkaRefund<'a> {
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
- connector_transaction_id: &refund.connector_transaction_id,
+ connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
- connector_refund_id: refund.connector_refund_id.as_ref(),
+ connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index f2150020c97..8f9f77878a1 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -1,4 +1,7 @@
-use common_utils::{id_type, types::MinorUnit};
+use common_utils::{
+ id_type,
+ types::{ConnectorTransactionIdTrait, MinorUnit},
+};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
@@ -40,9 +43,9 @@ impl<'a> KafkaRefundEvent<'a> {
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
- connector_transaction_id: &refund.connector_transaction_id,
+ connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
- connector_refund_id: refund.connector_refund_id.as_ref(),
+ connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index e115558995d..37387a01da3 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -482,7 +482,7 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(&connector::Worldline)))
}
enums::Connector::Worldpay => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Worldpay)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 88d9b433ecb..40335d5f2ab 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -63,6 +63,7 @@ impl PaymentAttemptExt for PaymentAttempt {
capture_sequence,
connector_capture_id: None,
connector_response_reference_id: None,
+ connector_capture_data: None,
})
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 4d753b59bc7..2146ab34271 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -10,6 +10,7 @@ use common_utils::{
ext_traits::{Encode, StringExt, ValueExt},
fp_utils::when,
pii,
+ types::ConnectorTransactionIdTrait,
};
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
@@ -1292,6 +1293,9 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
#[cfg(feature = "v1")]
impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self {
+ let connector_transaction_id = payment_attempt
+ .get_connector_payment_id()
+ .map(ToString::to_string);
Self {
attempt_id: payment_attempt.attempt_id,
status: payment_attempt.status,
@@ -1300,7 +1304,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
connector: payment_attempt.connector,
error_message: payment_attempt.error_reason,
payment_method: payment_attempt.payment_method,
- connector_transaction_id: payment_attempt.connector_transaction_id,
+ connector_transaction_id,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
created_at: payment_attempt.created_at,
@@ -1323,6 +1327,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
impl ForeignFrom<storage::Capture> for payments::CaptureResponse {
fn foreign_from(capture: storage::Capture) -> Self {
+ let connector_capture_id = capture.get_optional_connector_transaction_id().cloned();
Self {
capture_id: capture.capture_id,
status: capture.status,
@@ -1330,7 +1335,7 @@ impl ForeignFrom<storage::Capture> for payments::CaptureResponse {
currency: capture.currency,
connector: capture.connector,
authorized_attempt_id: capture.authorized_attempt_id,
- connector_capture_id: capture.connector_capture_id,
+ connector_capture_id,
capture_sequence: capture.capture_sequence,
error_message: capture.error_message,
error_code: capture.error_code,
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 1f7d75fba83..122989a82cf 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -2,7 +2,10 @@ use api_models::{
enums::Connector::{DummyConnector4, DummyConnector7},
user::sample_data::SampleDataRequest,
};
-use common_utils::{id_type, types::MinorUnit};
+use common_utils::{
+ id_type,
+ types::{ConnectorTransactionId, MinorUnit},
+};
use diesel_models::{user::sample_data::PaymentAttemptBatchNew, RefundNew};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentIntent;
@@ -253,10 +256,12 @@ pub async fn generate_sample_data(
tax_details: None,
skip_external_tax_calculation: None,
};
+ let (connector_transaction_id, connector_transaction_data) =
+ ConnectorTransactionId::form_id_and_data(attempt_id.clone());
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
payment_id: payment_id.clone(),
- connector_transaction_id: Some(attempt_id.clone()),
+ connector_transaction_id: Some(connector_transaction_id),
merchant_id: merchant_id.clone(),
status: match is_failed_payment {
true => common_enums::AttemptStatus::Failure,
@@ -333,18 +338,21 @@ pub async fn generate_sample_data(
organization_id: org_id.clone(),
shipping_cost: None,
order_tax_amount: None,
+ connector_transaction_data,
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
refunds_count += 1;
+ let (connector_transaction_id, connector_transaction_data) =
+ ConnectorTransactionId::form_id_and_data(attempt_id.clone());
Some(RefundNew {
refund_id: common_utils::generate_id_with_default_len("test"),
internal_reference_id: common_utils::generate_id_with_default_len("test"),
external_reference_id: None,
payment_id: payment_id.clone(),
- attempt_id: attempt_id.clone(),
+ attempt_id,
merchant_id: merchant_id.clone(),
- connector_transaction_id: attempt_id.clone(),
+ connector_transaction_id,
connector_refund_id: None,
description: Some("This is a sample refund".to_string()),
created_at,
@@ -369,6 +377,8 @@ pub async fn generate_sample_data(
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
organization_id: org_id.clone(),
+ connector_refund_data: None,
+ connector_transaction_data,
})
} else {
None
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index f61770a5bde..2b20ed4cf16 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -30,6 +30,7 @@ api_key = "Bearer MyApiKey"
[worldpay]
api_key = "api_key"
key1 = "key1"
+api_secret = "Merchant Identifier"
[payu]
api_key = "Bearer MyApiKey"
diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs
index d4f6e167ff8..451aa398eb7 100644
--- a/crates/router/tests/connectors/worldpay.rs
+++ b/crates/router/tests/connectors/worldpay.rs
@@ -20,7 +20,7 @@ impl utils::Connector for Worldpay {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Worldpay;
utils::construct_connector_data_old(
- Box::new(&Worldpay),
+ Box::new(Worldpay::new()),
types::Connector::Worldpay,
types::api::GetToken::Connector,
None,
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index 943ef1f36f7..54377e45267 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -97,13 +97,13 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
},
};
- match kv_wrapper::<DieselReverseLookup, _, _>(
+ match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>(
self,
KvOperation::SetNx(&created_rev_lookup, redis_entry),
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id),
},
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))?
.try_into_setnx()
@@ -140,13 +140,13 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
storage_enums::MerchantStorageScheme::RedisKv => {
let redis_fut = async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselReverseLookup>::Get,
PartitionKey::CombinationKey {
combination: &format!("reverse_lookup_{id}"),
},
- )
+ ))
.await?
.try_into_get()
};
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 9053b7561ad..231f72bd731 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -1,6 +1,10 @@
#[cfg(feature = "v2")]
use common_utils::types::keymanager::KeyManagerState;
-use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found};
+use common_utils::{
+ errors::CustomResult,
+ fallback_reverse_lookup_not_found,
+ types::{ConnectorTransactionId, ConnectorTransactionIdTrait},
+};
use diesel_models::{
enums::{
MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,
@@ -556,7 +560,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
- match kv_wrapper::<PaymentAttempt, _, _>(
+ match Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::HSetNx(
&field,
@@ -564,7 +568,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -628,7 +632,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
- let old_connector_transaction_id = &this.connector_transaction_id;
+ let old_connector_transaction_id = &this.get_connector_payment_id();
let old_preprocessing_id = &this.preprocessing_step_id;
let updated_attempt = PaymentAttempt::from_storage_model(
payment_attempt
@@ -653,7 +657,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
match (
old_connector_transaction_id,
- &updated_attempt.connector_transaction_id,
+ &updated_attempt.get_connector_payment_id(),
) {
(None, Some(connector_transaction_id)) => {
add_connector_txn_id_to_reverse_lookup(
@@ -661,7 +665,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
- connector_transaction_id.as_str(),
+ connector_transaction_id,
storage_scheme,
)
.await?;
@@ -673,7 +677,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
key_str.as_str(),
&this.merchant_id,
updated_attempt.attempt_id.as_str(),
- connector_transaction_id.as_str(),
+ connector_transaction_id,
storage_scheme,
)
.await?;
@@ -710,11 +714,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
(_, _) => {}
}
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry),
key,
- )
+ ))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hset()
@@ -798,7 +802,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key).await?.try_into_hget()
+ Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget()
},
|| async {self.router_store.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(connector_transaction_id, payment_id, merchant_id, storage_scheme).await},
))
@@ -839,11 +843,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let pattern = "pa_*";
let redis_fut = async {
- let kv_result = kv_wrapper::<PaymentAttempt, _, _>(
+ let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
- )
+ ))
.await?
.try_into_scan();
kv_result.and_then(|mut payment_attempts| {
@@ -898,11 +902,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let pattern = "pa_*";
let redis_fut = async {
- let kv_result = kv_wrapper::<PaymentAttempt, _, _>(
+ let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>(
self,
KvOperation::<DieselPaymentAttempt>::Scan(pattern),
key,
- )
+ ))
.await?
.try_into_scan();
kv_result.and_then(|mut payment_attempts| {
@@ -974,11 +978,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
};
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -1031,9 +1035,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let field = format!("pa_{attempt_id}");
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&field), key)
- .await?
- .try_into_hget()
+ Box::pin(kv_wrapper(
+ self,
+ KvOperation::<DieselPaymentAttempt>::HGet(&field),
+ key,
+ ))
+ .await?
+ .try_into_hget()
},
|| async {
self.router_store
@@ -1094,11 +1102,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
};
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -1183,11 +1191,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -1237,9 +1245,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
};
Box::pin(try_redis_get_else_try_database_get(
async {
- kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key)
- .await?
- .try_into_scan()
+ Box::pin(kv_wrapper(
+ self,
+ KvOperation::<DieselPaymentAttempt>::Scan("pa_*"),
+ key,
+ ))
+ .await?
+ .try_into_scan()
},
|| async {
self.router_store
@@ -1367,6 +1379,11 @@ impl DataModelExt for PaymentAttempt {
type StorageModel = DieselPaymentAttempt;
fn to_storage_model(self) -> Self::StorageModel {
+ let (connector_transaction_id, connector_transaction_data) = self
+ .connector_transaction_id
+ .map(ConnectorTransactionId::form_id_and_data)
+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
+ .unwrap_or((None, None));
DieselPaymentAttempt {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
@@ -1383,7 +1400,7 @@ impl DataModelExt for PaymentAttempt {
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
- connector_transaction_id: self.connector_transaction_id,
+ connector_transaction_id,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
@@ -1437,12 +1454,16 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
+ connector_transaction_data,
shipping_cost: self.net_amount.get_shipping_cost(),
order_tax_amount: self.net_amount.get_order_tax_amount(),
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
+ let connector_transaction_id = storage_model
+ .get_optional_connector_transaction_id()
+ .cloned();
Self {
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
storage_model.amount,
@@ -1462,7 +1483,7 @@ impl DataModelExt for PaymentAttempt {
offer_amount: storage_model.offer_amount,
payment_method_id: storage_model.payment_method_id,
payment_method: storage_model.payment_method,
- connector_transaction_id: storage_model.connector_transaction_id,
+ connector_transaction_id,
capture_method: storage_model.capture_method,
capture_on: storage_model.capture_on,
confirm: storage_model.confirm,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index f5c3deeb18c..8ca63e79037 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -113,7 +113,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
.await
.change_context(StorageError::EncryptionError)?;
- match kv_wrapper::<DieselPaymentIntent, _, _>(
+ match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
@@ -121,7 +121,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -228,11 +228,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -316,11 +316,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let field = payment_id.get_hash_key_for_kv_store();
Box::pin(utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper::<DieselPaymentIntent, _, _>(
+ Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
},
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 33d73f99e5f..81d06a1cbd5 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -115,7 +115,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
- match kv_wrapper::<DieselPayoutAttempt, _, _>(
+ match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>(
self,
KvOperation::<DieselPayoutAttempt>::HSetNx(
&field,
@@ -123,7 +123,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -227,11 +227,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
_ => {}
}
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -284,11 +284,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -345,11 +345,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper(
+ Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
- )
+ ))
.await?
.try_into_hget()
},
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 2a49b01458f..9a94743da3f 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -134,7 +134,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
},
};
- match kv_wrapper::<DieselPayouts, _, _>(
+ match Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HSetNx(
&field,
@@ -142,7 +142,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
redis_entry,
),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
@@ -208,11 +208,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
},
};
- kv_wrapper::<(), _, _>(
+ Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry),
key,
- )
+ ))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
@@ -255,11 +255,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
let field = format!("po_{payout_id}");
Box::pin(utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper::<DieselPayouts, _, _>(
+ Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
},
@@ -312,11 +312,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
let field = format!("po_{payout_id}");
Box::pin(utils::try_redis_get_else_try_database_get(
async {
- kv_wrapper::<DieselPayouts, _, _>(
+ Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
- )
+ ))
.await?
.try_into_hget()
.map(Some)
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 74b1526fe8e..2fde935b670 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -312,8 +312,12 @@ where
Op::Find => MerchantStorageScheme::RedisKv,
Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
Op::Update(partition_key, field, Some(_updated_by)) => {
- match kv_wrapper::<D, _, _>(store, KvOperation::<D>::HGet(field), partition_key)
- .await
+ match Box::pin(kv_wrapper::<D, _, _>(
+ store,
+ KvOperation::<D>::HGet(field),
+ partition_key,
+ ))
+ .await
{
Ok(_) => {
metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(&metrics::CONTEXT, 1, &[]);
diff --git a/crates/test_utils/tests/sample_auth.toml b/crates/test_utils/tests/sample_auth.toml
index 08b24817c24..c7ec4f12c54 100644
--- a/crates/test_utils/tests/sample_auth.toml
+++ b/crates/test_utils/tests/sample_auth.toml
@@ -30,6 +30,7 @@ api_key = "Bearer MyApiKey"
[worldpay]
api_key = "api_key"
key1 = "key1"
+api_secret = "Merchant Identifier"
[payu]
api_key = "Bearer MyApiKey"
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
index ea7b4f09fd7..c2d1b7483c1 100644
--- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
+++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
@@ -1069,7 +1069,7 @@ export const connectorDetails = {
status: 400,
body: {
error:
- "Json deserialize error: unknown variant `United`, expected one of `AED`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BWP`, `BYN`, `BZD`, `CAD`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SZL`, `THB`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`",
+ "Json deserialize error: unknown variant `United`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL`",
},
},
},
diff --git a/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql
new file mode 100644
index 00000000000..8008535f877
--- /dev/null
+++ b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql
@@ -0,0 +1,11 @@
+ALTER TABLE payment_attempt
+DROP COLUMN IF EXISTS connector_transaction_data;
+
+ALTER TABLE refund
+DROP COLUMN IF EXISTS connector_refund_data;
+
+ALTER TABLE refund
+DROP COLUMN IF EXISTS connector_transaction_data;
+
+ALTER TABLE captures
+DROP COLUMN IF EXISTS connector_capture_data;
\ No newline at end of file
diff --git a/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql
new file mode 100644
index 00000000000..adab6dd3edf
--- /dev/null
+++ b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql
@@ -0,0 +1,11 @@
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS connector_transaction_data VARCHAR(512);
+
+ALTER TABLE refund
+ADD COLUMN IF NOT EXISTS connector_refund_data VARCHAR(512);
+
+ALTER TABLE refund
+ADD COLUMN IF NOT EXISTS connector_transaction_data VARCHAR(512);
+
+ALTER TABLE captures
+ADD COLUMN IF NOT EXISTS connector_capture_data VARCHAR(512);
\ No newline at end of file
diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql
index cfc769e70e1..519bef65cbb 100644
--- a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql
+++ b/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql
@@ -38,4 +38,5 @@ ALTER TABLE payment_attempt DROP COLUMN payment_method_type_v2,
DROP COLUMN routing_result,
DROP COLUMN authentication_applied,
DROP COLUMN external_reference_id,
- DROP COLUMN tax_on_surcharge;
+ DROP COLUMN tax_on_surcharge,
+ DROP COLUMN connector_payment_data;
diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql
index 520bbdf6e7e..136bc550811 100644
--- a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql
+++ b/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql
@@ -41,4 +41,5 @@ ADD COLUMN payment_method_type_v2 VARCHAR,
ADD COLUMN routing_result JSONB,
ADD COLUMN authentication_applied "AuthenticationType",
ADD COLUMN external_reference_id VARCHAR(128),
- ADD COLUMN tax_on_surcharge BIGINT;
+ ADD COLUMN tax_on_surcharge BIGINT,
+ ADD COLUMN connector_payment_data VARCHAR(512);
diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql
similarity index 98%
rename from v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql
rename to v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql
index 65e90b126fb..2cdb0296033 100644
--- a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql
+++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql
@@ -76,6 +76,7 @@ ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64) NOT NULL,
ADD COLUMN offer_amount bigint,
ADD COLUMN payment_method VARCHAR,
ADD COLUMN connector_transaction_id VARCHAR(64),
+ ADD COLUMN connector_transaction_data VARCHAR(512),
ADD COLUMN capture_method "CaptureMethod",
ADD COLUMN capture_on TIMESTAMP,
ADD COLUMN mandate_id VARCHAR(64),
diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql
similarity index 98%
rename from v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql
rename to v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql
index 55b0b19d0b4..48ae811bf34 100644
--- a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql
+++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql
@@ -74,6 +74,7 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id,
DROP COLUMN offer_amount,
DROP COLUMN payment_method,
DROP COLUMN connector_transaction_id,
+ DROP COLUMN connector_transaction_data,
DROP COLUMN capture_method,
DROP COLUMN capture_on,
DROP COLUMN mandate_id,
| 2024-09-26T10:48:20Z |
## Description
Described in #6116
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Strengthens worldpay connector's integration.
## How did you test it?
Things to test
1. No 3DS payment using auto capture
2. No 3DS payment using manual capture (full amount captures)
3. Refunds
4. Payments Sync
5. Backwards compatibility
Notes
- Refunds cannot be tested as WP relies only on webhooks to update the status to settled (succeeded in HS). Webhook URLs are configured asynchronously by reaching out to them
- For manually updating the status to succeeded state and testing refunds, RSA key pairs can be created and webhook updates can be sent manually by configuring the MCA during creation (attach manually created private key in `merchant_secret` during MCA creation for WP)
- For WP's webhook body, refer this - https://developer.worldpay.com/products/access/events/signature
<details>
<summary>1. Create and capture</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data-raw '{
"amount": 30,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 30,
"customer_id": "default_cust",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "debit",
"connector": [
"worldpay"
],
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_NZqQvZ8fcOPBh9G8DGYL",
"merchant_id": "merchant_1727351469",
"status": "processing",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": null,
"connector": "worldpay",
"client_secret": "pay_NZqQvZ8fcOPBh9G8DGYL_secret_pS12cS9WGzDVePcuToPS",
"created": "2024-09-26T11:56:54.387Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "default_cust",
"created_at": 1727351814,
"expires": 1727355414,
"secret": "epk_acfbbc3281c148dd987b6132993fea2d"
},
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLnb6ueU9CbFGwfx591hAsgQIRSoXyZaKoMjxP1EcfaiTUMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83h2J9B9mwlKgm3S:taO:ZbBw8gpCy5HM2WoIeZ0:XaCCrRM9QKRvbI4hUfmMTrs3ETMXutYDlb4dag7xGA2Qa4Ttn9WFEcXNtvDKZy5OJFs3A==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:11:54.387Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T11:56:55.183Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>2. Create a payment using manual capture</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data-raw '{
"amount": 30,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"amount_to_capture": 30,
"customer_id": "default_cust",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "debit",
"connector": [
"worldpay"
],
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "requires_capture",
"amount": 30,
"net_amount": 30,
"amount_capturable": 30,
"amount_received": null,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "default_cust",
"created_at": 1727352819,
"expires": 1727356419,
"secret": "epk_6524fd56e9334269b3da878638480886"
},
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:13:40.443Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
cURL (capture)
curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_jGgKDnT9zDIpkNIbAU44DdT8uzauyY5huxSuQbqmgsvMmiTVnYVY6kNRE1xZtrnC' \
--data '{}'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "succeeded",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": 30,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:14:26.304Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>3. Full amount refunds</summary>
cURL
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data '{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
Response
{
"refund_id": "ref_GX50lP3TOZ5LEBgkCt3o",
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-09-26T12:17:08.162Z",
"updated_at": "2024-09-26T12:17:09.220Z",
"connector": "worldpay",
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"charges": null
}
</details>
<details>
<summary>4. Retrieve payment</summary>
cURL
curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "succeeded",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": 30,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": [
{
"refund_id": "ref_GX50lP3TOZ5LEBgkCt3o",
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-09-26T12:17:08.162Z",
"updated_at": "2024-09-26T12:17:09.220Z",
"connector": "worldpay",
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"charges": null
}
],
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:14:26.304Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>5. Backwards compatibility</summary>
1. Create a new txn in existing application
cURL
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1ty6UhSj8fnfhCQCpepIQXI3x22TPuzM5kWasidjCtlc0Am2ZaNRzfwU94hyXMjB' \
--data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","amount_to_capture":100,"customer_id":"default_cust","email":"guest@example.com","name":"John Doe","phone":"999999999","phone_country_code":"+1","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"}},"connector":["stripe"],"payment_method_data":{"card":{"card_number":"4242424242424242","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","card_cvc":"123"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"nl-NL","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"}}'
Response
{"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"default_cust","created_at":1729081502,"expires":1729085102,"secret":"epk_eb2cedad9dd440f2871464e3b6255f2e"},"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
2. Fetch the same payment in new application
cURL
curl --location --request GET 'http://localhost:8080/payments/pay_lzpTmYZBcWkTipqMfYaR?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_G3dnuM0z1Jjij7fFSo8pGC02QrgBgDB3wulB18mtqGiVkWnAq0vyoaCsQSXxbBrt'
Response
{"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":[{"refund_id":"ref_fxU4gvgDk3oPteI1wy4P","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:14.725Z","updated_at":"2024-10-16T12:25:18.559Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_oHm62P61wXjq7sx7vskd","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:11.356Z","updated_at":"2024-10-16T12:25:12.371Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_xSdJ24sgZQf4qDyDpUfj","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:13.069Z","updated_at":"2024-10-16T12:25:14.019Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null}],"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
</details> | 39d89f23b6ae85c4f91a52bb0d970277b43237d8 | Things to test
1. No 3DS payment using auto capture
2. No 3DS payment using manual capture (full amount captures)
3. Refunds
4. Payments Sync
5. Backwards compatibility
Notes
- Refunds cannot be tested as WP relies only on webhooks to update the status to settled (succeeded in HS). Webhook URLs are configured asynchronously by reaching out to them
- For manually updating the status to succeeded state and testing refunds, RSA key pairs can be created and webhook updates can be sent manually by configuring the MCA during creation (attach manually created private key in `merchant_secret` during MCA creation for WP)
- For WP's webhook body, refer this - https://developer.worldpay.com/products/access/events/signature
<details>
<summary>1. Create and capture</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data-raw '{
"amount": 30,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 30,
"customer_id": "default_cust",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "debit",
"connector": [
"worldpay"
],
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_NZqQvZ8fcOPBh9G8DGYL",
"merchant_id": "merchant_1727351469",
"status": "processing",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": null,
"connector": "worldpay",
"client_secret": "pay_NZqQvZ8fcOPBh9G8DGYL_secret_pS12cS9WGzDVePcuToPS",
"created": "2024-09-26T11:56:54.387Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "default_cust",
"created_at": 1727351814,
"expires": 1727355414,
"secret": "epk_acfbbc3281c148dd987b6132993fea2d"
},
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLnb6ueU9CbFGwfx591hAsgQIRSoXyZaKoMjxP1EcfaiTUMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83h2J9B9mwlKgm3S:taO:ZbBw8gpCy5HM2WoIeZ0:XaCCrRM9QKRvbI4hUfmMTrs3ETMXutYDlb4dag7xGA2Qa4Ttn9WFEcXNtvDKZy5OJFs3A==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:11:54.387Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T11:56:55.183Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>2. Create a payment using manual capture</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data-raw '{
"amount": 30,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"amount_to_capture": 30,
"customer_id": "default_cust",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "debit",
"connector": [
"worldpay"
],
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "requires_capture",
"amount": 30,
"net_amount": 30,
"amount_capturable": 30,
"amount_received": null,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "default_cust",
"created_at": 1727352819,
"expires": 1727356419,
"secret": "epk_6524fd56e9334269b3da878638480886"
},
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:13:40.443Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
cURL (capture)
curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_jGgKDnT9zDIpkNIbAU44DdT8uzauyY5huxSuQbqmgsvMmiTVnYVY6kNRE1xZtrnC' \
--data '{}'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "succeeded",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": 30,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:14:26.304Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>3. Full amount refunds</summary>
cURL
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \
--data '{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
Response
{
"refund_id": "ref_GX50lP3TOZ5LEBgkCt3o",
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-09-26T12:17:08.162Z",
"updated_at": "2024-09-26T12:17:09.220Z",
"connector": "worldpay",
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"charges": null
}
</details>
<details>
<summary>4. Retrieve payment</summary>
cURL
curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN'
Response
{
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"merchant_id": "merchant_1727351469",
"status": "succeeded",
"amount": 30,
"net_amount": 30,
"amount_capturable": 0,
"amount_received": 30,
"connector": "worldpay",
"client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG",
"created": "2024-09-26T12:13:39.556Z",
"currency": "USD",
"customer_id": "default_cust",
"customer": {
"id": "default_cust",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": [
{
"refund_id": "ref_GX50lP3TOZ5LEBgkCt3o",
"payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq",
"amount": 30,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-09-26T12:17:08.162Z",
"updated_at": "2024-09-26T12:17:09.220Z",
"connector": "worldpay",
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"charges": null
}
],
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_UANp3p6unZQH3GOhADuU",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T12:28:39.555Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T12:14:26.304Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
</details>
<details>
<summary>5. Backwards compatibility</summary>
1. Create a new txn in existing application
cURL
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1ty6UhSj8fnfhCQCpepIQXI3x22TPuzM5kWasidjCtlc0Am2ZaNRzfwU94hyXMjB' \
--data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","amount_to_capture":100,"customer_id":"default_cust","email":"guest@example.com","name":"John Doe","phone":"999999999","phone_country_code":"+1","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"}},"connector":["stripe"],"payment_method_data":{"card":{"card_number":"4242424242424242","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","card_cvc":"123"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"nl-NL","color_depth":24,"screen_height":723,"screen_width":1536,"time_zone":0,"java_enabled":true,"java_script_enabled":true,"ip_address":"127.0.0.1"}}'
Response
{"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"default_cust","created_at":1729081502,"expires":1729085102,"secret":"epk_eb2cedad9dd440f2871464e3b6255f2e"},"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
2. Fetch the same payment in new application
cURL
curl --location --request GET 'http://localhost:8080/payments/pay_lzpTmYZBcWkTipqMfYaR?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_G3dnuM0z1Jjij7fFSo8pGC02QrgBgDB3wulB18mtqGiVkWnAq0vyoaCsQSXxbBrt'
Response
{"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":[{"refund_id":"ref_fxU4gvgDk3oPteI1wy4P","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:14.725Z","updated_at":"2024-10-16T12:25:18.559Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_oHm62P61wXjq7sx7vskd","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:11.356Z","updated_at":"2024-10-16T12:25:12.371Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_xSdJ24sgZQf4qDyDpUfj","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:13.069Z","updated_at":"2024-10-16T12:25:14.019Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null}],"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
</details>
| [
"api-reference-v2/openapi_spec.json",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/common_enums/src/enums.rs",
"crates/common_utils/src/consts.rs",
"crates/common_... | |
juspay/hyperswitch | juspay__hyperswitch-6094 | Bug: [FIX] keymanager config if disabled
| diff --git a/config/development.toml b/config/development.toml
index 6e56d5bb14d..a607dd94a16 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -13,7 +13,7 @@ use_xray_generator = false
bg_metrics_collection_interval_in_secs = 15
[key_manager]
-url = "http://localhost:5000"
+enabled = false
# TODO: Update database credentials before running application
[master_database]
diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs
index abcb7aa87f7..078f1f3fcd8 100644
--- a/crates/common_utils/src/types/keymanager.rs
+++ b/crates/common_utils/src/types/keymanager.rs
@@ -25,7 +25,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct KeyManagerState {
- pub enabled: Option<bool>,
+ pub enabled: bool,
pub url: String,
pub client_idle_timeout: Option<u64>,
#[cfg(feature = "km_forward_x_request_id")]
diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs
index 0ff37b0bc29..983528dee98 100644
--- a/crates/hyperswitch_domain_models/src/type_encryption.rs
+++ b/crates/hyperswitch_domain_models/src/type_encryption.rs
@@ -101,7 +101,7 @@ mod encrypt {
fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
#[cfg(feature = "encryption_service")]
{
- _state.enabled.unwrap_or_default()
+ _state.enabled
}
#[cfg(not(feature = "encryption_service"))]
{
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 5719e111759..86bcb687b11 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -12461,16 +12461,3 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
),
])
}
-
-impl Default for super::settings::KeyManagerConfig {
- fn default() -> Self {
- Self {
- enabled: None,
- url: String::from("localhost:5000"),
- #[cfg(feature = "keymanager_mtls")]
- ca: String::default().into(),
- #[cfg(feature = "keymanager_mtls")]
- cert: String::default().into(),
- }
- }
-}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 8c893b88319..5a204f8508c 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -232,14 +232,22 @@ impl SecretsHandler for settings::KeyManagerConfig {
let keyconfig = value.get_inner();
#[cfg(feature = "keymanager_mtls")]
- let ca = _secret_management_client
- .get_secret(keyconfig.ca.clone())
- .await?;
+ let ca = if keyconfig.enabled {
+ _secret_management_client
+ .get_secret(keyconfig.ca.clone())
+ .await?
+ } else {
+ keyconfig.ca.clone()
+ };
#[cfg(feature = "keymanager_mtls")]
- let cert = _secret_management_client
- .get_secret(keyconfig.cert.clone())
- .await?;
+ let cert = if keyconfig.enabled {
+ _secret_management_client
+ .get_secret(keyconfig.cert.clone())
+ .await?
+ } else {
+ keyconfig.ca.clone()
+ };
Ok(value.transition_state(|keyconfig| Self {
#[cfg(feature = "keymanager_mtls")]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 675b8c44e2a..de45252dbf3 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -213,9 +213,10 @@ pub struct KvConfig {
pub soft_kill: Option<bool>,
}
-#[derive(Debug, Deserialize, Clone)]
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
pub struct KeyManagerConfig {
- pub enabled: Option<bool>,
+ pub enabled: bool,
pub url: String,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
@@ -859,6 +860,8 @@ impl Settings<SecuredSecret> {
.map(|x| x.get_inner().validate())
.transpose()?;
+ self.key_manager.get_inner().validate()?;
+
Ok(())
}
}
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 67db7b1266c..62b5c08a198 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -222,3 +222,25 @@ impl super::settings::NetworkTokenizationService {
})
}
}
+
+impl super::settings::KeyManagerConfig {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::fp_utils::when;
+
+ #[cfg(feature = "keymanager_mtls")]
+ when(
+ self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Invalid CA or Certificate for Keymanager.".into(),
+ ))
+ },
+ )?;
+
+ when(self.enabled && self.url.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Invalid URL for Keymanager".into(),
+ ))
+ })
+ }
+}
| 2024-09-26T07:16:23Z |
## Description
<!-- Describe your changes in detail -->
This fixes unnecessary failure when url and cert for the keymanager is not provided in the config but keymanager is disabled.
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 the keymanager is disabled in the config, there's no reason to provide `url` and `cert` for keymanager since they won't be used. This PR adds a check which checks if keymanager is enabled and only fail for these configs missing if keymanager is enabled
## How did you test 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 cannot be tested on any environment | 962b9978d651e3cc9185b2f6f849c7f255868077 |
This cannot be tested on any environment
| [
"config/development.toml",
"crates/common_utils/src/types/keymanager.rs",
"crates/hyperswitch_domain_models/src/type_encryption.rs",
"crates/router/src/configs/defaults.rs",
"crates/router/src/configs/secrets_transformers.rs",
"crates/router/src/configs/settings.rs",
"crates/router/src/configs/validatio... | |
juspay/hyperswitch | juspay__hyperswitch-6090 | Bug: restructure `Samsung Pay` connector wallet details
We need to restructure the Samsung Pay session token data stored in the connector wallet details as going forward we will add support for samsung pay payments with hyperswitch credentials. Then the samsung pay payment can be done using either merchant's credentials or hyperswitch's credentials. If it is merchant's credentials, it needs to be provided in the time of the merchant connector account creation.
But when it comes to hyperswitch's credentials flow, merchant will provide only merchant specific business information (like merchant name that should be displayed to customer during the payment and merchant's business country). Whereas the private key or the required Samsung Pay certificates for the decryption will reside in the application env.
```
"connector_wallets_details": {
"samsung_pay": {
"merchant_credentials": {
"service_id": "samsung pay service id",
"merchant_display_name": "merchant name",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
```
```
"connector_wallets_details": {
"samsung_pay": {
"application_credentials": {
"merchant_display_name": "merchant name",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
``` | diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 456bb8e43a3..9d606dacb9f 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4908,20 +4908,37 @@ pub struct GpaySessionTokenData {
pub data: GpayMetaData,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SamsungPayCombinedMetadata {
+ // This is to support the Samsung Pay decryption flow with application credentials,
+ // where the private key, certificates, or any other information required for decryption
+ // will be obtained from the environment variables.
+ ApplicationCredentials(SamsungPayApplicationCredentials),
+ MerchantCredentials(SamsungPayMerchantCredentials),
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SamsungPaySessionTokenData {
#[serde(rename = "samsung_pay")]
- pub data: SamsungPayMetadata,
+ pub data: SamsungPayCombinedMetadata,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct SamsungPayMetadata {
+pub struct SamsungPayMerchantCredentials {
pub service_id: String,
pub merchant_display_name: String,
pub merchant_business_country: api_enums::CountryAlpha2,
pub allowed_brands: Vec<String>,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SamsungPayApplicationCredentials {
+ pub merchant_display_name: String,
+ pub merchant_business_country: api_enums::CountryAlpha2,
+ pub allowed_brands: Vec<String>,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkMetaData {
pub client_id: String,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 5bd81897dd8..ee657bc3949 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -502,7 +502,7 @@ fn create_samsung_pay_session_token(
router_data: &types::PaymentsSessionRouterData,
header_payload: api_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
- let samsung_pay_wallet_details = router_data
+ let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
@@ -527,18 +527,30 @@ fn create_samsung_pay_session_token(
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?;
+ let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
+ payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
+ samsung_pay_merchant_credentials,
+ ) => samsung_pay_merchant_credentials,
+ payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
+ _samsung_pay_application_credentials,
+ ) => Err(errors::ApiErrorResponse::NotSupported {
+ message: "Samsung Pay decryption flow with application credentials is not implemented"
+ .to_owned(),
+ })?,
+ };
+
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
- service_id: samsung_pay_wallet_details.data.service_id,
+ service_id: samsung_pay_wallet_details.service_id,
order_number: router_data.payment_id.clone(),
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
- name: samsung_pay_wallet_details.data.merchant_display_name,
+ name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
- country_code: samsung_pay_wallet_details.data.merchant_business_country,
+ country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
@@ -546,7 +558,7 @@ fn create_samsung_pay_session_token(
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
- allowed_brands: samsung_pay_wallet_details.data.allowed_brands,
+ allowed_brands: samsung_pay_wallet_details.allowed_brands,
},
)),
}),
| 2024-09-26T06:27:47Z |
## Description
<!-- Describe your changes in detail -->
We need to restructure the Samsung Pay session token data stored in the connector wallet details as going forward we will add support for samsung pay payments with hyperswitch credentials. Then the samsung pay payment can be done using either merchant's credentials or hyperswitch's credentials. If it is merchant's credentials, it needs to be provided in the time of the merchant connector account creation.
But when it comes to hyperswitch's credentials flow, merchant will provide only merchant specific business information (like merchant name that should be displayed to customer during the payment and merchant's business country). Whereas the private key or the required Samsung Pay certificates for the decryption will reside in the application env.
```
"connector_wallets_details": {
"samsung_pay": {
"merchant_credentials": {
"service_id": "samsung pay service id",
"merchant_display_name": "merchant name",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
```
```
"connector_wallets_details": {
"samsung_pay": {
"application_credentials": {
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
},
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"application_credentials": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1727248481"
}'
```
```
{
"payment_id": "pay_wySk2SloqGsTbSB8ficv",
"merchant_id": "merchant_1727343230",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_wySk2SloqGsTbSB8ficv_secret_LDsqsymJeHNbX6X6tGW6",
"created": "2024-09-26T13:33:39.781Z",
"currency": "USD",
"customer_id": "cu_1727248481",
"customer": {
"id": "cu_1727248481",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727248481",
"created_at": 1727357619,
"expires": 1727361219,
"secret": "epk_780a72fc4a0d48338eeb3f029191723e"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_xEdgnpJ0oxDZrkzS02MR",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T13:48:39.780Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T13:33:39.842Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key:' \
--data '{
"payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD",
"wallets": [],
"client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN"
}'
```
```
{
"payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD",
"client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_GEoTU1wJGcWqs0vQ9TLD",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
``` | 962b9978d651e3cc9185b2f6f849c7f255868077 |
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"application_credentials": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1727248481"
}'
```
```
{
"payment_id": "pay_wySk2SloqGsTbSB8ficv",
"merchant_id": "merchant_1727343230",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_wySk2SloqGsTbSB8ficv_secret_LDsqsymJeHNbX6X6tGW6",
"created": "2024-09-26T13:33:39.781Z",
"currency": "USD",
"customer_id": "cu_1727248481",
"customer": {
"id": "cu_1727248481",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727248481",
"created_at": 1727357619,
"expires": 1727361219,
"secret": "epk_780a72fc4a0d48338eeb3f029191723e"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_xEdgnpJ0oxDZrkzS02MR",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-26T13:48:39.780Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-26T13:33:39.842Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key:' \
--data '{
"payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD",
"wallets": [],
"client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN"
}'
```
```
{
"payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD",
"client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_GEoTU1wJGcWqs0vQ9TLD",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
| [
"crates/api_models/src/payments.rs",
"crates/router/src/core/payments/flows/session_flow.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6086 | Bug: feat(analytics): add card network feature
Add a filter in payment analytics for the card network column | diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index e0235c67bed..149c77212a0 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -280,7 +280,10 @@ impl HealthCheck for OpenSearchClient {
if health.status != OpenSearchHealthStatus::Red {
Ok(())
} else {
- Err(QueryExecutionError::DatabaseError.into())
+ Err::<(), error_stack::Report<QueryExecutionError>>(
+ QueryExecutionError::DatabaseError.into(),
+ )
+ .attach_printable_lazy(|| format!("Opensearch cluster health is red: {health:?}"))
}
}
}
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index dca42b6802e..f41e1719450 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -296,6 +296,7 @@ pub async fn get_filters(
PaymentDimensions::ClientSource => fil.client_source,
PaymentDimensions::ClientVersion => fil.client_version,
PaymentDimensions::ProfileId => fil.profile_id,
+ PaymentDimensions::CardNetwork => fil.card_network,
})
.collect::<Vec<String>>();
res.query_data.push(FilterValue {
diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs
index 8e62c77a81f..094fd574169 100644
--- a/crates/analytics/src/payments/filters.rs
+++ b/crates/analytics/src/payments/filters.rs
@@ -59,4 +59,5 @@ pub struct PaymentFilterRow {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
+ pub card_network: Option<String>,
}
diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs
index f5139a9ea2b..b7984a19ea3 100644
--- a/crates/analytics/src/payments/types.rs
+++ b/crates/analytics/src/payments/types.rs
@@ -65,6 +65,25 @@ where
.add_filter_in_range_clause(PaymentDimensions::ProfileId, &self.profile_id)
.attach_printable("Error adding profile id filter")?;
}
+ if !self.card_network.is_empty() {
+ let card_networks: Vec<String> = self
+ .card_network
+ .iter()
+ .flat_map(|cn| {
+ [
+ format!("\"{cn}\""),
+ cn.to_string(),
+ format!("\"{cn}\"").to_uppercase(),
+ ]
+ })
+ .collect();
+ builder
+ .add_filter_in_range_clause(
+ PaymentDimensions::CardNetwork,
+ card_networks.as_slice(),
+ )
+ .attach_printable("Error adding card network filter")?;
+ }
Ok(())
}
}
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 76a5f5a0918..e9395439209 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -489,6 +489,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
Ok(Self {
currency,
status,
@@ -499,6 +503,7 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
client_source,
client_version,
profile_id,
+ card_network,
})
}
}
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index 40ff4bf2607..c474d47ee63 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -7,7 +7,8 @@ use common_utils::id_type;
use super::{NameDescription, TimeRange};
use crate::enums::{
- AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType,
+ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod,
+ PaymentMethodType,
};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
@@ -29,6 +30,8 @@ pub struct PaymentFilters {
#[serde(default)]
pub client_version: Vec<String>,
#[serde(default)]
+ pub card_network: Vec<CardNetwork>,
+ #[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
}
@@ -64,6 +67,7 @@ pub enum PaymentDimensions {
ClientSource,
ClientVersion,
ProfileId,
+ CardNetwork,
}
#[derive(
| 2024-09-25T20:51:06Z |
## Description
<!-- Describe your changes in detail -->
- Add card network analytics filter in payment analytics
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
<img width="431" alt="image" src="https://github.com/user-attachments/assets/d209f786-a967-4245-a780-e9539a5c7469"> | 9a605afe372a0602127090da59e35ac9ca7396e1 |
<img width="431" alt="image" src="https://github.com/user-attachments/assets/d209f786-a967-4245-a780-e9539a5c7469">
| [
"crates/analytics/src/opensearch.rs",
"crates/analytics/src/payments/core.rs",
"crates/analytics/src/payments/filters.rs",
"crates/analytics/src/payments/types.rs",
"crates/analytics/src/sqlx.rs",
"crates/api_models/src/analytics/payments.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6028 | Bug: [FEATURE] Implement Paze Wallet
### Feature Description
Integrate paze wallet
https://www.paze.com/
### Possible Implementation
Integrate paze wallet
https://www.paze.com/
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 388ccb79a66..44ac1d3e08d 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -5592,6 +5592,11 @@
"type": "object",
"description": "This field contains the Samsung Pay certificates and credentials",
"nullable": true
+ },
+ "paze": {
+ "type": "object",
+ "description": "This field contains the Paze certificates and credentials",
+ "nullable": true
}
},
"additionalProperties": false
@@ -12548,6 +12553,7 @@
"open_banking_uk",
"pay_bright",
"paypal",
+ "paze",
"pix",
"pay_safe_card",
"przelewy24",
@@ -17138,6 +17144,39 @@
}
}
},
+ "PazeSessionTokenResponse": {
+ "type": "object",
+ "required": [
+ "client_id",
+ "client_name",
+ "client_profile_id"
+ ],
+ "properties": {
+ "client_id": {
+ "type": "string",
+ "description": "Paze Client ID"
+ },
+ "client_name": {
+ "type": "string",
+ "description": "Client Name to be displayed on the Paze screen"
+ },
+ "client_profile_id": {
+ "type": "string",
+ "description": "Paze Client Profile ID"
+ }
+ }
+ },
+ "PazeWalletData": {
+ "type": "object",
+ "required": [
+ "complete_response"
+ ],
+ "properties": {
+ "complete_response": {
+ "type": "string"
+ }
+ }
+ },
"PhoneDetails": {
"type": "object",
"properties": {
@@ -19377,6 +19416,27 @@
}
]
},
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PazeSessionTokenResponse"
+ },
+ {
+ "type": "object",
+ "required": [
+ "wallet_name"
+ ],
+ "properties": {
+ "wallet_name": {
+ "type": "string",
+ "enum": [
+ "paze"
+ ]
+ }
+ }
+ }
+ ]
+ },
{
"type": "object",
"required": [
@@ -20551,6 +20611,17 @@
}
}
},
+ {
+ "type": "object",
+ "required": [
+ "paze"
+ ],
+ "properties": {
+ "paze": {
+ "$ref": "#/components/schemas/PazeWalletData"
+ }
+ }
+ },
{
"type": "object",
"required": [
diff --git a/config/config.example.toml b/config/config.example.toml
index 54f0d1a27a4..c0358d91a26 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -540,6 +540,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.stax]
credit = { currency = "USD" }
@@ -581,6 +582,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key
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 generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key
+[paze_decrypt_keys]
+paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365
+paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem
+
[applepay_merchant_configs]
# Run below command to get common merchant identifier for applepay in shell
#
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index db43cac979b..5dce5be9c96 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -29,6 +29,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key
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 generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key
+[paze_decrypt_keys]
+paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365
+paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem
+
[applepay_merchant_configs]
common_merchant_identifier = "APPLE_PAY_COMMON_MERCHANT_IDENTIFIER" # Refer to config.example.toml to learn how you can generate this value
merchant_cert = "APPLE_PAY_MERCHANT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index dbb4161ec5d..4f742a61698 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -307,6 +307,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.nexixpay]
credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index c100ccf46de..c25b70d6ba0 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -281,6 +281,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.nexixpay]
credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 89aea282764..28f5a4e0575 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -284,6 +284,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.nexixpay]
credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
diff --git a/config/development.toml b/config/development.toml
index f0e26172514..0153c6ef102 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -453,6 +453,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.nexixpay]
credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
@@ -617,6 +618,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY"
apple_pay_merchant_cert = "APPLE_PAY_MERCHNAT_CERTIFICATE"
apple_pay_merchant_cert_key = "APPLE_PAY_MERCHNAT_CERTIFICATE_KEY"
+[paze_decrypt_keys]
+paze_private_key = "PAZE_PRIVATE_KEY"
+paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE"
+
[generic_link]
[generic_link.payment_method_collect]
sdk_url = "http://localhost:9050/HyperLoader.js"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 1b9ef294dc0..5ffe5df138f 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -420,6 +420,7 @@ debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
samsung_pay = { currency = "USD,GBP,EUR" }
+paze = { currency = "USD" }
[pm_filters.nexixpay]
credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" }
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 6e7f4f29d03..8f24bdf65bc 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1558,6 +1558,10 @@ pub struct ConnectorWalletDetails {
#[serde(skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<Object>)]
pub samsung_pay: Option<pii::SecretSerdeValue>,
+ /// This field contains the Paze certificates and credentials
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub paze: Option<pii::SecretSerdeValue>,
}
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 9cafc37af54..a758d457858 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1930,6 +1930,7 @@ impl GetPaymentMethodType for WalletData {
Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
+ Self::Paze(_) => api_enums::PaymentMethodType::Paze,
Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,
Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,
Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,
@@ -2819,6 +2820,8 @@ pub enum WalletData {
PaypalRedirect(PaypalRedirection),
/// The wallet data for Paypal
PaypalSdk(PayPalWalletData),
+ /// The wallet data for Paze
+ Paze(PazeWalletData),
/// The wallet data for Samsung Pay
SamsungPay(Box<SamsungPayWalletData>),
/// Wallet data for Twint Redirection
@@ -2879,6 +2882,7 @@ impl GetAddressFromPaymentMethodData for WalletData {
| Self::GooglePayRedirect(_)
| Self::GooglePayThirdPartySdk(_)
| Self::PaypalSdk(_)
+ | Self::Paze(_)
| Self::SamsungPay(_)
| Self::TwintRedirect {}
| Self::VippsRedirect {}
@@ -2891,6 +2895,13 @@ impl GetAddressFromPaymentMethodData for WalletData {
}
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct PazeWalletData {
+ #[schema(value_type = String)]
+ pub complete_response: Secret<String>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
@@ -4932,6 +4943,19 @@ pub struct GpaySessionTokenData {
pub data: GpayMetaData,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PazeSessionTokenData {
+ #[serde(rename = "paze")]
+ pub data: PazeMetadata,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PazeMetadata {
+ pub client_id: String,
+ pub client_name: String,
+ pub client_profile_id: String,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SamsungPayCombinedMetadata {
@@ -5138,10 +5162,23 @@ pub enum SessionToken {
ApplePay(Box<ApplepaySessionTokenResponse>),
/// Session token for OpenBanking PIS flow
OpenBanking(OpenBankingSessionToken),
+ /// The session response structure for Paze
+ Paze(Box<PazeSessionTokenResponse>),
/// Whenever there is no session token response or an error in session response
NoSessionTokenReceived,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct PazeSessionTokenResponse {
+ /// Paze Client ID
+ pub client_id: String,
+ /// Client Name to be displayed on the Paze screen
+ pub client_name: String,
+ /// Paze Client Profile ID
+ pub client_profile_id: String,
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(untagged)]
pub enum GpaySessionTokenResponse {
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 528f38ac61a..5ab05c9a688 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1593,6 +1593,7 @@ pub enum PaymentMethodType {
OpenBankingUk,
PayBright,
Paypal,
+ Paze,
Pix,
PaySafeCard,
Przelewy24,
diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs
index db4162a8bb1..4fba749ef63 100644
--- a/crates/common_enums/src/transformers.rs
+++ b/crates/common_enums/src/transformers.rs
@@ -1843,6 +1843,7 @@ impl From<PaymentMethodType> for PaymentMethod {
PaymentMethodType::OnlineBankingThailand => Self::BankRedirect,
PaymentMethodType::OnlineBankingPoland => Self::BankRedirect,
PaymentMethodType::OnlineBankingSlovakia => Self::BankRedirect,
+ PaymentMethodType::Paze => Self::Wallet,
PaymentMethodType::PermataBankTransfer => Self::BankTransfer,
PaymentMethodType::Pix => Self::BankTransfer,
PaymentMethodType::Pse => Self::BankTransfer,
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 68ade2909b4..88997691eb6 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -56,7 +56,10 @@ impl DashboardRequestPayload {
| (Connector::Stripe, WeChatPay) => {
Some(api_models::enums::PaymentExperience::DisplayQrCode)
}
- (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) => {
+ (_, GooglePay)
+ | (_, ApplePay)
+ | (_, PaymentMethodType::SamsungPay)
+ | (_, PaymentMethodType::Paze) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
_ => Some(api_models::enums::PaymentExperience::RedirectToUrl),
diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs
index 0d2f959c702..136cdf4d981 100644
--- a/crates/euclid/src/frontend/dir/enums.rs
+++ b/crates/euclid/src/frontend/dir/enums.rs
@@ -91,6 +91,7 @@ pub enum WalletType {
Cashapp,
Venmo,
Mifinity,
+ Paze,
}
#[derive(
diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs
index 33d368e9696..da589ec3748 100644
--- a/crates/euclid/src/frontend/dir/lowering.rs
+++ b/crates/euclid/src/frontend/dir/lowering.rs
@@ -58,6 +58,7 @@ impl From<enums::WalletType> for global_enums::PaymentMethodType {
enums::WalletType::Cashapp => Self::Cashapp,
enums::WalletType::Venmo => Self::Venmo,
enums::WalletType::Mifinity => Self::Mifinity,
+ enums::WalletType::Paze => Self::Paze,
}
}
}
diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs
index 3e35bcd391c..de0b619b120 100644
--- a/crates/euclid/src/frontend/dir/transformers.rs
+++ b/crates/euclid/src/frontend/dir/transformers.rs
@@ -188,6 +188,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet
global_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
+ global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index eab8d878f05..c4ca017cec7 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -366,6 +366,9 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
FiuuPaymentMethodData::try_from(decrypt_data)
}
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Fiuu"))?
+ }
}
}
WalletData::AliPayQr(_)
@@ -384,6 +387,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
index 4986e8d5f32..772f2af209e 100644
--- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
@@ -74,6 +74,7 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
index d0525921632..a12434a460a 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
@@ -182,6 +182,9 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP
"Mollie"
))?
}
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Mollie"))?
+ }
}),
},
)))
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index 4e2b30a574b..ad09e7445d4 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -119,6 +119,7 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
@@ -263,6 +264,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest {
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Square"),
)?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Square"))?
+ }
},
amount_money: SquarePaymentsAmountData {
amount: item.request.amount,
diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index f7b2016a370..686178e9621 100644
--- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -82,6 +82,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Stax"))?
+ }
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
@@ -99,6 +102,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Stax"))?
+ }
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 4c7c9adaf8e..66b8081b0f2 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -1781,6 +1781,7 @@ pub enum PaymentMethodDataType {
MobilePayRedirect,
PaypalRedirect,
PaypalSdk,
+ Paze,
SamsungPay,
TwintRedirect,
VippsRedirect,
@@ -1898,6 +1899,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType {
hyperswitch_domain_models::payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
hyperswitch_domain_models::payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
hyperswitch_domain_models::payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk,
+ hyperswitch_domain_models::payment_method_data::WalletData::Paze(_) => Self::Paze,
hyperswitch_domain_models::payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay,
hyperswitch_domain_models::payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect,
hyperswitch_domain_models::payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 9f505f26712..3ccfabf021c 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -117,6 +117,7 @@ pub enum WalletData {
MobilePayRedirect(Box<MobilePayRedirection>),
PaypalRedirect(PaypalRedirection),
PaypalSdk(PayPalWalletData),
+ Paze(PazeWalletData),
SamsungPay(Box<SamsungPayWalletData>),
TwintRedirect {},
VippsRedirect {},
@@ -134,6 +135,12 @@ pub struct MifinityData {
pub language_preference: Option<String>,
}
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct PazeWalletData {
+ pub complete_response: Secret<String>,
+}
+
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
@@ -689,6 +696,9 @@ impl From<api_models::payments::WalletData> for WalletData {
token: paypal_sdk_data.token,
})
}
+ api_models::payments::WalletData::Paze(paze_data) => {
+ Self::Paze(PazeWalletData::from(paze_data))
+ }
api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data)))
}
@@ -754,6 +764,14 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
}
}
+impl From<api_models::payments::PazeWalletData> for PazeWalletData {
+ fn from(value: api_models::payments::PazeWalletData) -> Self {
+ Self {
+ complete_response: value.complete_response,
+ }
+ }
+}
+
impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData {
fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self {
Self {
@@ -1388,6 +1406,7 @@ impl GetPaymentMethodType for WalletData {
Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
+ Self::Paze(_) => api_enums::PaymentMethodType::Paze,
Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,
Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,
Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index cd8ac85594e..b41b42eaa2d 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -220,6 +220,7 @@ pub struct AccessToken {
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<ApplePayPredecryptData>),
+ PazeDecrypt(Box<PazeDecryptedData>),
}
#[derive(Debug, Clone, serde::Deserialize)]
@@ -241,6 +242,69 @@ pub struct ApplePayCryptogramData {
pub eci_indicator: Option<String>,
}
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazeDecryptedData {
+ pub client_id: Secret<String>,
+ pub profile_id: String,
+ pub token: PazeToken,
+ pub payment_card_network: common_enums::enums::CardNetwork,
+ pub dynamic_data: Vec<PazeDynamicData>,
+ pub billing_address: PazeAddress,
+ pub consumer: PazeConsumer,
+ pub eci: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazeToken {
+ pub payment_token: cards::CardNumber,
+ pub token_expiration_month: Secret<String>,
+ pub token_expiration_year: Secret<String>,
+ pub payment_account_reference: Secret<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazeDynamicData {
+ pub dynamic_data_value: Option<Secret<String>>,
+ pub dynamic_data_type: Option<String>,
+ pub dynamic_data_expiration: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazeAddress {
+ pub name: Option<Secret<String>>,
+ pub line1: Option<Secret<String>>,
+ pub line2: Option<Secret<String>>,
+ pub line3: Option<Secret<String>>,
+ pub city: Option<Secret<String>>,
+ pub state: Option<Secret<String>>,
+ pub zip: Option<Secret<String>>,
+ pub country_code: Option<common_enums::enums::CountryAlpha2>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazeConsumer {
+ // This is consumer data not customer data.
+ pub first_name: Option<Secret<String>>,
+ pub last_name: Option<Secret<String>>,
+ pub full_name: Secret<String>,
+ pub email_address: common_utils::pii::Email,
+ pub mobile_number: Option<PazePhoneNumber>,
+ pub country_code: Option<common_enums::enums::CountryAlpha2>,
+ pub language_code: Option<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PazePhoneNumber {
+ pub country_code: Secret<String>,
+ pub phone_number: Secret<String>,
+}
+
#[derive(Debug, Default, Clone)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index 2ec0cbe8031..e897292d6ff 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -146,6 +146,7 @@ fn get_dir_value_payment_method(
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
+ api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
}
}
diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs
index 758a0dd3de0..1a340aa91d3 100644
--- a/crates/kgraph_utils/src/transformers.rs
+++ b/crates/kgraph_utils/src/transformers.rs
@@ -307,6 +307,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
api_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
+ api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
}
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index a76726eb8ac..24fbadc0a59 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -389,6 +389,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
+ api_models::payments::PazeWalletData,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
@@ -445,6 +446,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
+ api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 05a2c72ba94..bc44068030b 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -323,6 +323,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
api_models::payments::PaymentsCreateIntentResponse,
+ api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
@@ -358,6 +359,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
+ api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 0f25477802c..dbdba189ed1 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -178,6 +178,27 @@ impl SecretsHandler for settings::ApplePayDecryptConfig {
}
}
+#[async_trait::async_trait]
+impl SecretsHandler for settings::PazeDecryptConfig {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let paze_decrypt_keys = value.get_inner();
+
+ let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!(
+ secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()),
+ secret_management_client
+ .get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()),
+ )?;
+
+ Ok(value.transition_state(|_| Self {
+ paze_private_key,
+ paze_private_key_passphrase,
+ }))
+ }
+}
+
#[async_trait::async_trait]
impl SecretsHandler for settings::ApplepayMerchantConfigs {
async fn convert_to_raw_secret(
@@ -388,6 +409,17 @@ pub(crate) async fn fetch_raw_secrets(
.await
.expect("Failed to decrypt applepay decrypt configs");
+ #[allow(clippy::expect_used)]
+ let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys {
+ Some(
+ settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client)
+ .await
+ .expect("Failed to decrypt paze decrypt configs"),
+ )
+ } else {
+ None
+ };
+
#[allow(clippy::expect_used)]
let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret(
conf.applepay_merchant_configs,
@@ -479,6 +511,7 @@ pub(crate) async fn fetch_raw_secrets(
#[cfg(feature = "payouts")]
payouts: conf.payouts,
applepay_decrypt_keys,
+ paze_decrypt_keys,
multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors,
applepay_merchant_configs,
lock_settings: conf.lock_settings,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 1124423714b..149ee2b8456 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -96,6 +96,7 @@ pub struct Settings<S: SecretState> {
pub payouts: Payouts,
pub payout_method_filters: ConnectorFilters,
pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>,
+ pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>,
pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors,
pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>,
pub lock_settings: LockSettings,
@@ -723,6 +724,12 @@ pub struct ApplePayDecryptConfig {
pub apple_pay_merchant_cert_key: Secret<String>,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct PazeDecryptConfig {
+ pub paze_private_key: Secret<String>,
+ pub paze_private_key_passphrase: Secret<String>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LockerBasedRecipientConnectorList {
@@ -864,6 +871,11 @@ impl Settings<SecuredSecret> {
.map(|x| x.get_inner().validate())
.transpose()?;
+ self.paze_decrypt_keys
+ .as_ref()
+ .map(|x| x.get_inner().validate())
+ .transpose()?;
+
self.key_manager.get_inner().validate()?;
Ok(())
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index f109fe3f773..7040998ccf0 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -236,6 +236,27 @@ impl super::settings::NetworkTokenizationService {
}
}
+impl super::settings::PazeDecryptConfig {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::fp_utils::when;
+
+ when(self.paze_private_key.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "paze_private_key must not be empty".into(),
+ ))
+ })?;
+
+ when(
+ self.paze_private_key_passphrase.is_default_or_empty(),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "paze_private_key_passphrase must not be empty".into(),
+ ))
+ },
+ )
+ }
+}
+
impl super::settings::KeyManagerConfig {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 46f312b38f2..abd99fae18c 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -120,6 +120,7 @@ impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> for Pay
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect { .. }
| domain::WalletData::VippsRedirect { .. }
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 810551e0cb7..e5215022e94 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -218,6 +218,7 @@ impl ConnectorValidation for Adyen {
| PaymentMethodType::Pse
| PaymentMethodType::LocalBankTransfer
| PaymentMethodType::Efecty
+ | PaymentMethodType::Paze
| PaymentMethodType::PagoEfectivo
| PaymentMethodType::PromptPay
| PaymentMethodType::RedCompra
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 50ce6aea0f4..4cc392c57bc 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2149,6 +2149,7 @@ impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)>
| domain::WalletData::GooglePayRedirect(_)
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::WeChatPayQr(_)
| domain::WalletData::CashappQr(_)
| domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index 4d84f64534e..868a4767c31 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -254,6 +254,7 @@ fn get_wallet_details(
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 868409dafc7..e352d8b79bc 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -1747,6 +1747,7 @@ fn get_wallet_data(
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index b987a6717a1..ab6367eeb6e 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -297,6 +297,7 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -977,6 +978,9 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
"Bank Of America"
))?
}
+ types::PaymentMethodToken::PazeDecrypt(_) => Err(
+ unimplemented_payment_method!("Paze", "Bank Of America"),
+ )?,
},
None => {
let email = item.router_data.request.get_email()?;
@@ -1051,6 +1055,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -2328,6 +2333,9 @@ impl TryFrom<(&types::SetupMandateRouterData, domain::ApplePayWalletData)>
"Manual",
"Bank Of America"
))?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Bank Of America"))?
+ }
},
None => PaymentInformation::from(&apple_pay_data),
};
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 6ebcdf0e765..b156aafb6ef 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -369,6 +369,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index 5fd6b0e6a2e..a48e49a10cc 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -180,6 +180,7 @@ fn get_wallet_type(wallet_data: &domain::WalletData) -> Result<String, errors::C
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 05d8c1c559d..29f741d8bdc 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -1591,6 +1591,9 @@ impl
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
)?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Braintree"))?
+ }
},
transaction: transaction_body,
},
@@ -1689,6 +1692,9 @@ fn get_braintree_redirect_form(
"Simplified",
"Braintree"
))?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Braintree"))?
+ }
},
bin: match card_details {
domain::PaymentMethodData::Card(card_details) => {
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 223256155cf..2950fdb6bd1 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -106,6 +106,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -301,6 +302,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Checkout"))?
+ }
},
})),
domain::WalletData::ApplePay(_) => {
@@ -327,6 +331,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
},
)))
}
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Checkout"))?
+ }
}
}
domain::WalletData::AliPayQr(_)
@@ -345,6 +352,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 38bb016ff25..8a6c3c075ff 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -176,6 +176,9 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
types::PaymentMethodToken::Token(_) => Err(
unimplemented_payment_method!("Apple Pay", "Manual", "Cybersource"),
)?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Cybersource"))?
+ }
},
None => (
PaymentInformation::ApplePayToken(Box::new(
@@ -221,6 +224,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -1322,6 +1326,92 @@ impl
}
}
+impl
+ TryFrom<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Box<hyperswitch_domain_models::router_data::PazeDecryptedData>,
+ )> for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, paze_data): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Box<hyperswitch_domain_models::router_data::PazeDecryptedData>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let email = item.router_data.request.get_email()?;
+ let (first_name, last_name) = match paze_data.billing_address.name {
+ Some(name) => {
+ let (first_name, last_name) = name
+ .peek()
+ .split_once(' ')
+ .map(|(first, last)| (first.to_string(), last.to_string()))
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "billing_address.name",
+ })?;
+ (Secret::from(first_name), Secret::from(last_name))
+ }
+ None => (
+ item.router_data.get_billing_first_name()?,
+ item.router_data.get_billing_last_name()?,
+ ),
+ };
+ let bill_to = BillTo {
+ first_name: Some(first_name),
+ last_name: Some(last_name),
+ address1: paze_data.billing_address.line1,
+ locality: paze_data.billing_address.city.map(|city| city.expose()),
+ administrative_area: Some(Secret::from(
+ //Paze wallet is currently supported in US only
+ common_enums::UsStatesAbbreviation::foreign_try_from(
+ paze_data
+ .billing_address
+ .state
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "billing_address.state",
+ })?
+ .peek()
+ .to_owned(),
+ )?
+ .to_string(),
+ )),
+ postal_code: paze_data.billing_address.zip,
+ country: paze_data.billing_address.country_code,
+ email,
+ };
+ let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
+
+ let payment_information =
+ PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation {
+ tokenized_card: NetworkTokenizedCard {
+ number: paze_data.token.payment_token,
+ expiration_month: paze_data.token.token_expiration_month,
+ expiration_year: paze_data.token.token_expiration_year,
+ cryptogram: Some(paze_data.token.payment_account_reference),
+ transaction_type: "1".to_string(),
+ },
+ }));
+
+ let processing_information = ProcessingInformation::try_from((item, None, None))?;
+ let client_reference_information = ClientReferenceInformation::from(item);
+ let merchant_defined_information = item
+ .router_data
+ .request
+ .metadata
+ .clone()
+ .map(Vec::<MerchantDefinedInformation>::foreign_from);
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ consumer_authentication_information: None,
+ merchant_defined_information,
+ })
+ }
+}
+
impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
@@ -1645,6 +1735,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
"Cybersource"
))?
}
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Cybersource"))?
+ }
},
None => {
let email = item
@@ -1719,6 +1812,19 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
domain::WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((item, samsung_pay_data))
}
+ domain::WalletData::Paze(_) => {
+ match item.router_data.payment_method_token.clone() {
+ Some(types::PaymentMethodToken::PazeDecrypt(
+ paze_decrypted_data,
+ )) => Self::try_from((item, paze_decrypted_data)),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "Cybersource",
+ ),
+ )
+ .into()),
+ }
+ }
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index ff2f9d95026..4982aaf4d88 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -429,7 +429,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest {
let payment_method_token = item.get_payment_method_token()?;
let customer_bank_account = match payment_method_token {
types::PaymentMethodToken::Token(token) => Ok(token),
- types::PaymentMethodToken::ApplePayDecrypt(_) => {
+ types::PaymentMethodToken::ApplePayDecrypt(_)
+ | types::PaymentMethodToken::PazeDecrypt(_) => {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for selected payment method through Gocardless".to_string(),
))
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 0e6fab80584..2c3d3651284 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -598,6 +598,7 @@ impl
| common_enums::PaymentMethodType::OpenBankingUk
| common_enums::PaymentMethodType::PayBright
| common_enums::PaymentMethodType::Paypal
+ | common_enums::PaymentMethodType::Paze
| common_enums::PaymentMethodType::Pix
| common_enums::PaymentMethodType::PaySafeCard
| common_enums::PaymentMethodType::Przelewy24
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 0af3826c877..92b6b45785d 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -169,6 +169,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 547a38ad849..e0146bf2eda 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -493,6 +493,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -556,6 +557,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -714,6 +716,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 55b2fbe4176..5bf72133384 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -722,6 +722,7 @@ fn get_wallet_details(
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect { .. }
| domain::WalletData::VippsRedirect { .. }
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 069a51ae52e..57b04cdca17 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -558,6 +558,7 @@ impl
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 5d987174273..99e04018632 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -326,6 +326,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index f280d3a42a2..d9728174f84 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -914,6 +914,7 @@ where
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index e0ab598d76d..b4aa66a1c49 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -403,6 +403,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -715,6 +716,9 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"),
)?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Payme"))?
+ }
};
Ok(Self {
buyer_email,
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 4f5ab133735..41fd533309e 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -490,6 +490,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 13c0395cf9f..e206fe0e0ae 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -282,6 +282,7 @@ impl TryFrom<&domain::WalletData> for Shift4PaymentMethod {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index f9fd519241a..68bab815d65 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -737,6 +737,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
| enums::PaymentMethodType::MandiriVa
| enums::PaymentMethodType::PermataBankTransfer
| enums::PaymentMethodType::PaySafeCard
+ | enums::PaymentMethodType::Paze
| enums::PaymentMethodType::Givex
| enums::PaymentMethodType::Benefit
| enums::PaymentMethodType::Knet
@@ -1062,6 +1063,7 @@ impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> {
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -1478,6 +1480,7 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -1809,6 +1812,9 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent
wallet_name: "Apple Pay".to_string(),
})?
}
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(crate::unimplemented_payment_method!("Paze", "Stripe"))?
+ }
};
Some(StripePaymentMethodData::Wallet(
StripeWallet::ApplepayPayment(ApplepayPayment {
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index c66e1f2f65c..31afb0adf11 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -2638,6 +2638,7 @@ pub enum PaymentMethodDataType {
MobilePayRedirect,
PaypalRedirect,
PaypalSdk,
+ Paze,
SamsungPay,
TwintRedirect,
VippsRedirect,
@@ -2755,6 +2756,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk,
+ domain::payments::WalletData::Paze(_) => Self::Paze,
domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay,
domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect,
domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect,
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index be3cf4a1cef..ee34c26d670 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -135,6 +135,9 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
types::PaymentMethodToken::Token(_) => Err(
unimplemented_payment_method!("Apple Pay", "Manual", "Wellsfargo"),
)?,
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
+ }
},
None => (
PaymentInformation::ApplePayToken(Box::new(
@@ -180,6 +183,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -1158,6 +1162,9 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
"Wellsfargo"
))?
}
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
+ }
},
None => {
let email = item.router_data.request.get_email()?;
@@ -1242,6 +1249,7 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index de82e11548c..467a1cba902 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -83,6 +83,7 @@ fn fetch_payment_instrument(
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index d2e8ce40283..2b2e7e889e2 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -486,6 +486,7 @@ impl
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalSdk(_)
+ | domain::WalletData::Paze(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index c56bfaca913..aa4ff406a2c 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -234,6 +234,16 @@ pub enum ApplePayDecryptionError {
DerivingSharedSecretKeyFailed,
}
+#[derive(Debug, thiserror::Error)]
+pub enum PazeDecryptionError {
+ #[error("Failed to base64 decode input data")]
+ Base64DecodingFailed,
+ #[error("Failed to decrypt input data")]
+ DecryptionFailed,
+ #[error("Certificate parsing failed")]
+ CertificateParsingFailed,
+}
+
#[cfg(feature = "detailed_errors")]
pub mod error_stack_parsing {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 9f904116171..363d52cd8bf 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -34,13 +34,13 @@ use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
-use helpers::ApplePayData;
+use helpers::{decrypt_paze_token, ApplePayData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentIntentData;
pub use hyperswitch_domain_models::{
mandates::{CustomerAcceptance, MandateData},
payment_address::PaymentAddress,
- router_data::RouterData,
+ router_data::{PaymentMethodToken, RouterData},
router_request_types::CustomerDetails,
};
use masking::{ExposeInterface, PeekInterface, Secret};
@@ -1710,42 +1710,12 @@ where
&call_connector_action,
);
- // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay
- // and the connector supports Apple Pay predecrypt
- match &tokenization_action {
- TokenizationAction::DecryptApplePayToken(payment_processing_details)
- | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
- payment_processing_details,
- ) => {
- let apple_pay_data = match payment_data.get_payment_method_data() {
- Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
- wallet_data,
- ))) => Some(
- ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone()))
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .decrypt(
- &payment_processing_details.payment_processing_certificate,
- &payment_processing_details.payment_processing_certificate_key,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- ),
- _ => None,
- };
-
- let apple_pay_predecrypt = apple_pay_data
- .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
- "ApplePayPredecryptData",
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
-
- router_data.payment_method_token = Some(
- hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(
- Box::new(apple_pay_predecrypt),
- ),
- );
- }
- _ => (),
+ router_data.payment_method_token = if let Some(decrypted_token) =
+ add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await?
+ {
+ Some(decrypted_token)
+ } else {
+ router_data.payment_method_token
};
let payment_method_token_response = router_data
@@ -1853,6 +1823,83 @@ where
Ok((router_data, merchant_connector_account))
}
+pub async fn add_decrypted_payment_method_token<F, D>(
+ tokenization_action: TokenizationAction,
+ payment_data: &D,
+) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse>
+where
+ F: Send + Clone + Sync,
+ D: OperationSessionGetters<F> + Send + Sync + Clone,
+{
+ // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay
+ // and the connector supports Apple Pay predecrypt
+ match &tokenization_action {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ) => {
+ let apple_pay_data = match payment_data.get_payment_method_data() {
+ Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
+ wallet_data,
+ ))) => Some(
+ ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone()))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to parse apple pay token to json")?
+ .decrypt(
+ &payment_processing_details.payment_processing_certificate,
+ &payment_processing_details.payment_processing_certificate_key,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to decrypt apple pay token")?,
+ ),
+ _ => None,
+ };
+
+ let apple_pay_predecrypt = apple_pay_data
+ .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
+ "ApplePayPredecryptData",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "failed to parse decrypted apple pay response to ApplePayPredecryptData",
+ )?;
+
+ Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new(
+ apple_pay_predecrypt,
+ ))))
+ }
+ TokenizationAction::DecryptPazeToken(payment_processing_details) => {
+ let paze_data = match payment_data.get_payment_method_data() {
+ Some(domain::PaymentMethodData::Wallet(domain::WalletData::Paze(wallet_data))) => {
+ Some(
+ decrypt_paze_token(
+ wallet_data.clone(),
+ payment_processing_details.paze_private_key.clone(),
+ payment_processing_details
+ .paze_private_key_passphrase
+ .clone(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to decrypt paze token")?,
+ )
+ }
+ _ => None,
+ };
+ let paze_decrypted_data = paze_data
+ .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>(
+ "PazeDecryptedData",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to parse PazeDecryptedData")?;
+ Ok(Some(PaymentMethodToken::PazeDecrypt(Box::new(
+ paze_decrypted_data,
+ ))))
+ }
+ _ => Ok(None),
+ }
+}
+
pub async fn get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account: &helpers::MerchantConnectorAccountType,
key_store: &domain::MerchantKeyStore,
@@ -2642,59 +2689,87 @@ async fn decide_payment_method_tokenize_action(
pm_parent_token: Option<&str>,
is_connector_tokenization_enabled: bool,
apple_pay_flow: Option<domain::ApplePayFlow>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
) -> RouterResult<TokenizationAction> {
- match pm_parent_token {
- None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
- (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
- payment_processing_details,
- )
- }
- (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
- (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
- TokenizationAction::DecryptApplePayToken(payment_processing_details)
- }
- (false, _) => TokenizationAction::TokenizeInRouter,
- }),
- Some(token) => {
- let redis_conn = state
- .store
- .get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get redis connection")?;
-
- let key = format!(
- "pm_token_{}_{}_{}",
- token.to_owned(),
- payment_method,
- connector_name
- );
+ if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type {
+ // Paze generates a one time use network token which should not be tokenized in the connector or router.
+ match &state.conf.paze_decrypt_keys {
+ Some(paze_keys) => Ok(TokenizationAction::DecryptPazeToken(
+ PazePaymentProcessingDetails {
+ paze_private_key: paze_keys.get_inner().paze_private_key.clone(),
+ paze_private_key_passphrase: paze_keys
+ .get_inner()
+ .paze_private_key_passphrase
+ .clone(),
+ },
+ )),
+ None => Err(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch Paze configs"),
+ }
+ } else {
+ match pm_parent_token {
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ )
+ }
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ }
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
+ Some(token) => {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let key = format!(
+ "pm_token_{}_{}_{}",
+ token.to_owned(),
+ payment_method,
+ connector_name
+ );
- let connector_token_option = redis_conn
- .get_key::<Option<String>>(&key)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch the token from redis")?;
+ let connector_token_option = redis_conn
+ .get_key::<Option<String>>(&key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch the token from redis")?;
- match connector_token_option {
- Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)),
- None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
- (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
- payment_processing_details,
- )
- }
- (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
- (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
- TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ match connector_token_option {
+ Some(connector_token) => {
+ Ok(TokenizationAction::ConnectorToken(connector_token))
}
- (false, _) => TokenizationAction::TokenizeInRouter,
- }),
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (
+ true,
+ Some(domain::ApplePayFlow::Simplified(payment_processing_details)),
+ ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ),
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (
+ false,
+ Some(domain::ApplePayFlow::Simplified(payment_processing_details)),
+ ) => TokenizationAction::DecryptApplePayToken(payment_processing_details),
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
+ }
}
}
}
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
+pub struct PazePaymentProcessingDetails {
+ pub paze_private_key: Secret<String>,
+ pub paze_private_key_passphrase: Secret<String>,
+}
+
#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInRouter,
@@ -2704,6 +2779,7 @@ pub enum TokenizationAction {
SkipConnectorTokenization,
DecryptApplePayToken(payments_api::PaymentProcessingDetails),
TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails),
+ DecryptPazeToken(PazePaymentProcessingDetails),
}
#[cfg(feature = "v2")]
@@ -2791,6 +2867,7 @@ where
payment_data.get_token(),
is_connector_tokenization_enabled,
apple_pay_flow,
+ *payment_method_type,
)
.await?;
@@ -2846,6 +2923,9 @@ where
) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
payment_processing_details,
),
+ TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => {
+ TokenizationAction::DecryptPazeToken(paze_payment_processing_details)
+ }
};
(payment_data.to_owned(), connector_tokenization_action)
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index ee657bc3949..1785eee87c5 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -498,6 +498,34 @@ async fn create_applepay_session_token(
}
}
+fn create_paze_session_token(
+ router_data: &types::PaymentsSessionRouterData,
+ _header_payload: api_models::payments::HeaderPayload,
+) -> RouterResult<types::PaymentsSessionRouterData> {
+ let paze_wallet_details = router_data
+ .connector_wallets_details
+ .clone()
+ .parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData")
+ .change_context(errors::ConnectorError::NoConnectorWalletDetails)
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "connector_wallets_details".to_string(),
+ expected_format: "paze_metadata_format".to_string(),
+ })?;
+
+ Ok(types::PaymentsSessionRouterData {
+ response: Ok(types::PaymentsResponseData::SessionResponse {
+ session_token: payment_types::SessionToken::Paze(Box::new(
+ payment_types::PazeSessionTokenResponse {
+ client_id: paze_wallet_details.data.client_id,
+ client_name: paze_wallet_details.data.client_name,
+ client_profile_id: paze_wallet_details.data.client_profile_id,
+ },
+ )),
+ }),
+ ..router_data.clone()
+ })
+}
+
fn create_samsung_pay_session_token(
router_data: &types::PaymentsSessionRouterData,
header_payload: api_models::payments::HeaderPayload,
@@ -967,6 +995,7 @@ impl RouterDataSession for types::PaymentsSessionRouterData {
api::GetToken::PaypalSdkMetadata => {
create_paypal_sdk_session_token(state, self, connector, business_profile)
}
+ api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload),
api::GetToken::Connector => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Session,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index fbd1170ebad..a39b151bd27 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -30,7 +30,7 @@ use futures::future::Either;
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use hyperswitch_domain_models::{
mandates::MandateData,
- payment_method_data::GetPaymentMethodType,
+ payment_method_data::{GetPaymentMethodType, PazeWalletData},
payments::{
payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
PaymentIntent,
@@ -2545,6 +2545,7 @@ pub fn validate_payment_method_type_against_payment_method(
| api_enums::PaymentMethodType::KakaoPay
| api_enums::PaymentMethodType::Cashapp
| api_enums::PaymentMethodType::Mifinity
+ | api_enums::PaymentMethodType::Paze
),
api_enums::PaymentMethod::BankRedirect => matches!(
payment_method_type,
@@ -4624,6 +4625,9 @@ async fn get_and_merge_apple_pay_metadata(
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
+ paze: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.paze.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
@@ -4639,6 +4643,9 @@ async fn get_and_merge_apple_pay_metadata(
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
+ paze: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.paze.clone()),
}
}
};
@@ -4980,6 +4987,71 @@ impl ApplePayData {
}
}
+pub fn decrypt_paze_token(
+ paze_wallet_data: PazeWalletData,
+ paze_private_key: masking::Secret<String>,
+ paze_private_key_passphrase: masking::Secret<String>,
+) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> {
+ let decoded_paze_private_key = BASE64_ENGINE
+ .decode(paze_private_key.expose().as_bytes())
+ .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
+ let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase(
+ decoded_paze_private_key.as_slice(),
+ paze_private_key_passphrase.expose().as_bytes(),
+ )
+ .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
+ let decrypted_private_key_pem = String::from_utf8(
+ decrypted_private_key
+ .private_key_to_pem()
+ .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?,
+ )
+ .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
+ let decrypter = jwe::RSA_OAEP_256
+ .decrypter_from_pem(decrypted_private_key_pem)
+ .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
+
+ let paze_complete_response: Vec<&str> = paze_wallet_data
+ .complete_response
+ .peek()
+ .split('.')
+ .collect();
+ let encrypted_jwe_key = paze_complete_response
+ .get(1)
+ .ok_or(errors::PazeDecryptionError::DecryptionFailed)?
+ .to_string();
+ let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(encrypted_jwe_key)
+ .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
+ let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key)
+ .change_context(errors::PazeDecryptionError::DecryptionFailed)?;
+
+ let (deserialized_payload, _deserialized_header) =
+ jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter)
+ .change_context(errors::PazeDecryptionError::DecryptionFailed)?;
+ let encoded_secured_payload_element = String::from_utf8(deserialized_payload)
+ .change_context(errors::PazeDecryptionError::DecryptionFailed)?
+ .split('.')
+ .collect::<Vec<&str>>()
+ .get(1)
+ .ok_or(errors::PazeDecryptionError::DecryptionFailed)?
+ .to_string();
+ let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(encoded_secured_payload_element)
+ .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
+ let parsed_decrypted: serde_json::Value =
+ serde_json::from_slice(&decoded_secured_payload_element)
+ .change_context(errors::PazeDecryptionError::DecryptionFailed)?;
+ Ok(parsed_decrypted)
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct JwsBody {
+ pub payload_id: String,
+ pub session_id: String,
+ pub secured_payload: masking::Secret<String>,
+}
+
pub fn get_key_params_for_surcharge_details(
payment_method_data: &domain::PaymentMethodData,
) -> Option<(
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index cc8b839cc80..2e37d26cdec 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -492,6 +492,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken {
api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata,
api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata,
api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata,
+ api_models::enums::PaymentMethodType::Paze => Self::PazeMetadata,
_ => Self::Connector,
}
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 6815d2dfc4f..ee75536e7c9 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -133,6 +133,11 @@ where
message: "Apple Pay Decrypt token is not supported".to_string(),
})?
}
+ types::PaymentMethodToken::PazeDecrypt(_) => {
+ Err(errors::ApiErrorResponse::NotSupported {
+ message: "Paze Decrypt token is not supported".to_string(),
+ })?
+ }
};
Some((connector_name, token))
} else {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index c2ed06d9bad..e115558995d 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -177,6 +177,7 @@ pub enum GetToken {
SamsungPayMetadata,
ApplePayMetadata,
PaypalSdkMetadata,
+ PazeMetadata,
Connector,
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a75ef879daf..49d8d50442e 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -476,6 +476,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
| api_enums::PaymentMethodType::Dana
| api_enums::PaymentMethodType::MbWay
| api_enums::PaymentMethodType::MobilePay
+ | api_enums::PaymentMethodType::Paze
| api_enums::PaymentMethodType::SamsungPay
| api_enums::PaymentMethodType::Twint
| api_enums::PaymentMethodType::Vipps
| 2024-09-25T13:09:27Z |
## Description
<!-- Describe your changes in detail -->
New wallet Paze is integrated in Hyperswitch with Cybserource as the supported payment processor.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6028
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Paze Payments need to be tested via Cybersource:
1. Payments Connector - Create:
Request:
```
curl --location 'http://localhost:8080/account/merchant_1727784802/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "Hidden",
"api_key": "Hidden",
"key1": "Hidden"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paze",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"paze": {
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
},
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret"
},
"metadata": {
"city": "NY",
"unit": "245"
},
"business_country": "US",
"business_label": "default"
}'
```
Response:
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_default",
"merchant_connector_id": "mca_LaFobeWWU3nzVfEQnMid",
"profile_id": "pro_3BNSt57cBpRKDJzhCxfA",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "********************************",
"key1": "*************",
"api_secret": "****************************************"
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paze",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret",
"additional_secret": null
},
"metadata": {
"city": "NY",
"unit": "245"
},
"test_mode": true,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null,
"connector_wallets_details": {
"paze": {
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
}
}
```
2. Sessions Call:
Request:
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_1140ed2282ae444f83e6f632b93494c6' \
--data '{
"payment_id": "pay_pu2Qby7cIiVAwj83fN6i",
"wallets": [],
"client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq"
}'
```
Response:
```
{
"payment_id": "pay_pu2Qby7cIiVAwj83fN6i",
"client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq",
"session_token": [
{
"wallet_name": "paze",
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
]
}
```
3. Authorize Call:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QgqEI16yUU6qP3jOiSA3j2jbMhRbGL9JWvfXEwtTJuNgRESEP3sT8ERvUr0zfQlw' \
--data-raw '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"customer_id": "customer123",
"email": "guest@example.com",
"payment_method": "wallet",
"payment_method_type": "paze",
"payment_method_data": {
"wallet": {
"paze": {
"complete_response": "hidden"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
}
}'
```
Response:
```
{
"payment_id": "pay_zdsQ2IvNNzTzlXqRxcVf",
"merchant_id": "merchant_1727784802",
"status": "succeeded",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": 1234,
"connector": "cybersource",
"client_secret": "pay_zdsQ2IvNNzTzlXqRxcVf_secret_7KXFE67dATn1TB5tystW",
"created": "2024-10-02T19:01:05.077Z",
"currency": "USD",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paze",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1727895665,
"expires": 1727899265,
"secret": "epk_b224eba38d6043489989317e299307db"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7278956668186980703954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_zdsQ2IvNNzTzlXqRxcVf_1",
"payment_link": null,
"profile_id": "pro_3BNSt57cBpRKDJzhCxfA",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_Y57pUeM64cR6N1yMkABh",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-02T19:16:05.076Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-02T19:01:08.367Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | 2bc21cfc5e3e6d8403bec82fde14cfd01536f406 |
Paze Payments need to be tested via Cybersource:
1. Payments Connector - Create:
Request:
```
curl --location 'http://localhost:8080/account/merchant_1727784802/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "Hidden",
"api_key": "Hidden",
"key1": "Hidden"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paze",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"paze": {
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
},
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret"
},
"metadata": {
"city": "NY",
"unit": "245"
},
"business_country": "US",
"business_label": "default"
}'
```
Response:
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_default",
"merchant_connector_id": "mca_LaFobeWWU3nzVfEQnMid",
"profile_id": "pro_3BNSt57cBpRKDJzhCxfA",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "********************************",
"key1": "*************",
"api_secret": "****************************************"
},
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paze",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret",
"additional_secret": null
},
"metadata": {
"city": "NY",
"unit": "245"
},
"test_mode": true,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null,
"connector_wallets_details": {
"paze": {
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
}
}
```
2. Sessions Call:
Request:
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_1140ed2282ae444f83e6f632b93494c6' \
--data '{
"payment_id": "pay_pu2Qby7cIiVAwj83fN6i",
"wallets": [],
"client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq"
}'
```
Response:
```
{
"payment_id": "pay_pu2Qby7cIiVAwj83fN6i",
"client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq",
"session_token": [
{
"wallet_name": "paze",
"client_id": "Hidden",
"client_name": "Hidden",
"client_profile_id": "Hidden"
}
]
}
```
3. Authorize Call:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QgqEI16yUU6qP3jOiSA3j2jbMhRbGL9JWvfXEwtTJuNgRESEP3sT8ERvUr0zfQlw' \
--data-raw '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"customer_id": "customer123",
"email": "guest@example.com",
"payment_method": "wallet",
"payment_method_type": "paze",
"payment_method_data": {
"wallet": {
"paze": {
"complete_response": "hidden"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
}
}'
```
Response:
```
{
"payment_id": "pay_zdsQ2IvNNzTzlXqRxcVf",
"merchant_id": "merchant_1727784802",
"status": "succeeded",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": 1234,
"connector": "cybersource",
"client_secret": "pay_zdsQ2IvNNzTzlXqRxcVf_secret_7KXFE67dATn1TB5tystW",
"created": "2024-10-02T19:01:05.077Z",
"currency": "USD",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paze",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1727895665,
"expires": 1727899265,
"secret": "epk_b224eba38d6043489989317e299307db"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7278956668186980703954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_zdsQ2IvNNzTzlXqRxcVf_1",
"payment_link": null,
"profile_id": "pro_3BNSt57cBpRKDJzhCxfA",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_Y57pUeM64cR6N1yMkABh",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-02T19:16:05.076Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-02T19:01:08.367Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
| [
"api-reference-v2/openapi_spec.json",
"config/config.example.toml",
"config/deployments/env_specific.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/api_models... | |
juspay/hyperswitch | juspay__hyperswitch-6018 | Bug: pass Samsung Pay `public_key_hash` in the confirm call
The token received form Samsung Pay will be int the JWT format. The header of that will contain the `kid` which is the `public_key_hash`. This is needs to be passed to Cybersource in the confirm call. | diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index f0b84fc93c1..810551e0cb7 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -130,6 +130,7 @@ impl ConnectorValidation for Adyen {
}
},
PaymentMethodType::Ach
+ | PaymentMethodType::SamsungPay
| PaymentMethodType::Alma
| PaymentMethodType::Bacs
| PaymentMethodType::Givex
@@ -222,7 +223,6 @@ impl ConnectorValidation for Adyen {
| PaymentMethodType::RedCompra
| PaymentMethodType::RedPagos
| PaymentMethodType::CryptoCurrency
- | PaymentMethodType::SamsungPay
| PaymentMethodType::Evoucher
| PaymentMethodType::Cashapp
| PaymentMethodType::UpiCollect
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 9c596f5575c..864f77b55dd 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -6,8 +6,13 @@ use api_models::{
};
use base64::Engine;
use common_enums::FutureUsage;
-use common_utils::{ext_traits::ValueExt, pii, types::SemanticVersion};
+use common_utils::{
+ ext_traits::{OptionExt, ValueExt},
+ pii,
+ types::SemanticVersion,
+};
use error_stack::ResultExt;
+use josekit::jwt::decode_header;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -457,6 +462,14 @@ pub struct SamsungPayPaymentInformation {
tokenized_card: SamsungPayTokenizedCard,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SamsungPayFluidDataValue {
+ public_key_hash: Secret<String>,
+ version: String,
+ data: Secret<String>,
+}
+
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
@@ -1531,13 +1544,17 @@ impl
let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
+ let samsung_pay_fluid_data_value =
+ get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?;
+
+ let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to serialize samsung pay fluid data")?;
+
let payment_information =
PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation {
fluid_data: FluidData {
- value: Secret::from(
- consts::BASE64_ENGINE
- .encode(samsung_pay_data.payment_credential.token_data.data.peek()),
- ),
+ value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)),
descriptor: Some(
consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY),
),
@@ -1571,6 +1588,28 @@ impl
}
}
+fn get_samsung_pay_fluid_data_value(
+ samsung_pay_token_data: &hyperswitch_domain_models::payment_method_data::SamsungPayTokenData,
+) -> Result<SamsungPayFluidDataValue, error_stack::Report<errors::ConnectorError>> {
+ let samsung_pay_header = decode_header(samsung_pay_token_data.data.clone().peek())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("Failed to decode samsung pay header")?;
+
+ let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str());
+
+ let samsung_pay_fluid_data_value = SamsungPayFluidDataValue {
+ public_key_hash: Secret::new(
+ samsung_pay_kid_optional
+ .get_required_value("samsung pay public_key_hash")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?
+ .to_string(),
+ ),
+ version: samsung_pay_token_data.version.clone(),
+ data: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())),
+ };
+ Ok(samsung_pay_fluid_data_value)
+}
+
impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
for CybersourcePaymentsRequest
{
| 2024-09-25T05:31:12Z |
## Description
<!-- Describe your changes in detail -->
The token received form Samsung Pay will be int the JWT format. The header of that will contain the `kid` which is the `public_key_hash`. This is needs to be passed to Cybersource in the confirm call.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Test Samsung Pay flow
-> Enable Samsung Pay payment method for the connector (Cybersource)
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data '{
"amount": 100000,
"currency": "INR",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726743607"
}'
```
```
{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"merchant_id": "merchant_1727087901",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P",
"created": "2024-09-25T05:46:55.720Z",
"currency": "USD",
"customer_id": "cu_1727243216",
"customer": {
"id": "cu_1727243216",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727243216",
"created_at": 1727243215,
"expires": 1727246815,
"secret": "epk_af7b8c52b45e490bac3a87ec19188c46"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_avq4S1jpyTn6UkRb4hZc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-25T06:01:55.720Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-25T05:46:55.804Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_3ccbd5ee07844da0a0f7f7b746c3465c' \
--data '{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"wallets": [],
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P"
}'
```
```
{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_9oXGqEDD6bQTYhbLvC40",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Confirm call
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_i7CIay3cWADIXr8SlfpZUYnlSri7K5xgVeUsaE31Lvms3KstLwTHVoOby02qzez9' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "1661",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": "eyJhbGciOiJSU0ExXzUiLCJraWQiOiJKdnI0ZlM1L0N0dmx6Ly95cGZYK2xkQ1p4dFBIUVBNUHg4SzI5Ty9lZm1JPSIsInR5cCI6IkpPU0UiLCJjaGFubmVsU2VjdXJpdHlDb250ZXh0IjoiUlNBX1BLSSIsImVuYyI6IkExMjhHQ00ifQ.PC27m6Zz5arTvQuQAVgUDl4fczWtG8lAQwybchbD6v7UYalTz0fIo45ZFHHmlol7Q087pbH_2KPfGAi2dc3i-Akao1I-e7sL5VO4W19MWtnfN1cF2RpMmHIlLuOrqNUcqJQ2WFqhXFpzr1C9hL47nWYc4tTScI2V4kdbERFxMIKpDIHH0SL1xGHl1v5l3oXeehY-sfMFEKpKqINHQs7mxZB0Cw9HLw6WvyJ2IBh-pgzEAvMSFrHpYI2TedKbVSafSDgmHfc6vLcfiHxNXenCiHYYRHEVqqu-MAJ1svfS31fZUCAv3NRLo4G886auZvc-XWaLrwTT-5EoaUsOo8BH6w.yQY3X4j_pVJ6o7Bu.ocIct0IUNZLaHhdbi3LVjWZ3bcy22_2vV-vD7JfwyPPIACGzrZmtdKSB6eEPdo7RGtWJQ2prmDYQsL3VUP9dKRnVGbpnGJsL5Cv5D4p9JX4iPrlgL5GeFNmhHsIFDNmVnepZ-swXhI1p4SzmTpwd16X8Hupt9lQXiTRPkerJHExCpqw3ZZCcTiV2sSm53wfeYOpXYZJ2DvIB51Hpsi1eHyI8F6dDqJ0h6XUBTZzy_5iLWVvuppS2.3RlqL07i3F_Zh_xzjTt_rA"
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_R5DGXtaNE918aMsxrmmY",
"merchant_id": "merchant_1727087901",
"status": "succeeded",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": 1,
"connector": "cybersource",
"client_secret": "pay_R5DGXtaNE918aMsxrmmY_secret_uYxRmMDDtbMNF0oJpFp5",
"created": "2024-09-25T05:48:27.368Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1727243307,
"expires": 1727246907,
"secret": "epk_26d63c60253046abb4e95d28c66addb5"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7272433088196497503955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_R5DGXtaNE918aMsxrmmY_1",
"payment_link": null,
"profile_id": "pro_avq4S1jpyTn6UkRb4hZc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NMxxPseaV1nTfu7vHpR5",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-25T06:03:27.368Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-25T05:48:30.388Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
``` | 2a10b09a2f7c6bcf0b9b7c23b5b88066e1d0f029 |
Test Samsung Pay flow
-> Enable Samsung Pay payment method for the connector (Cybersource)
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data '{
"amount": 100000,
"currency": "INR",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726743607"
}'
```
```
{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"merchant_id": "merchant_1727087901",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P",
"created": "2024-09-25T05:46:55.720Z",
"currency": "USD",
"customer_id": "cu_1727243216",
"customer": {
"id": "cu_1727243216",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1727243216",
"created_at": 1727243215,
"expires": 1727246815,
"secret": "epk_af7b8c52b45e490bac3a87ec19188c46"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_avq4S1jpyTn6UkRb4hZc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-25T06:01:55.720Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-25T05:46:55.804Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_3ccbd5ee07844da0a0f7f7b746c3465c' \
--data '{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"wallets": [],
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P"
}'
```
```
{
"payment_id": "pay_9oXGqEDD6bQTYhbLvC40",
"client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "Stripe"
},
"shipping_address_required": false,
"email_required": false,
"shipping_address_parameters": {
"phone_number_required": false
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
],
"billing_address_required": false
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
],
"transaction_info": {
"country_code": "US",
"currency_code": "USD",
"total_price_status": "Final",
"total_price": "1000.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_9oXGqEDD6bQTYhbLvC40",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "1000.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.com.hyperswitch.checkout"
},
"connector": "cybersource",
"delayed_session_token": false,
"sdk_next_action": {
"next_action": "confirm"
},
"connector_reference_id": null,
"connector_sdk_public_key": null,
"connector_merchant_id": null
}
]
}
```
-> Confirm call
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_i7CIay3cWADIXr8SlfpZUYnlSri7K5xgVeUsaE31Lvms3KstLwTHVoOby02qzez9' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "1661",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": "eyJhbGciOiJSU0ExXzUiLCJraWQiOiJKdnI0ZlM1L0N0dmx6Ly95cGZYK2xkQ1p4dFBIUVBNUHg4SzI5Ty9lZm1JPSIsInR5cCI6IkpPU0UiLCJjaGFubmVsU2VjdXJpdHlDb250ZXh0IjoiUlNBX1BLSSIsImVuYyI6IkExMjhHQ00ifQ.PC27m6Zz5arTvQuQAVgUDl4fczWtG8lAQwybchbD6v7UYalTz0fIo45ZFHHmlol7Q087pbH_2KPfGAi2dc3i-Akao1I-e7sL5VO4W19MWtnfN1cF2RpMmHIlLuOrqNUcqJQ2WFqhXFpzr1C9hL47nWYc4tTScI2V4kdbERFxMIKpDIHH0SL1xGHl1v5l3oXeehY-sfMFEKpKqINHQs7mxZB0Cw9HLw6WvyJ2IBh-pgzEAvMSFrHpYI2TedKbVSafSDgmHfc6vLcfiHxNXenCiHYYRHEVqqu-MAJ1svfS31fZUCAv3NRLo4G886auZvc-XWaLrwTT-5EoaUsOo8BH6w.yQY3X4j_pVJ6o7Bu.ocIct0IUNZLaHhdbi3LVjWZ3bcy22_2vV-vD7JfwyPPIACGzrZmtdKSB6eEPdo7RGtWJQ2prmDYQsL3VUP9dKRnVGbpnGJsL5Cv5D4p9JX4iPrlgL5GeFNmhHsIFDNmVnepZ-swXhI1p4SzmTpwd16X8Hupt9lQXiTRPkerJHExCpqw3ZZCcTiV2sSm53wfeYOpXYZJ2DvIB51Hpsi1eHyI8F6dDqJ0h6XUBTZzy_5iLWVvuppS2.3RlqL07i3F_Zh_xzjTt_rA"
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_R5DGXtaNE918aMsxrmmY",
"merchant_id": "merchant_1727087901",
"status": "succeeded",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": 1,
"connector": "cybersource",
"client_secret": "pay_R5DGXtaNE918aMsxrmmY_secret_uYxRmMDDtbMNF0oJpFp5",
"created": "2024-09-25T05:48:27.368Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "samsungpay@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "samsungpay@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1727243307,
"expires": 1727246907,
"secret": "epk_26d63c60253046abb4e95d28c66addb5"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7272433088196497503955",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_R5DGXtaNE918aMsxrmmY_1",
"payment_link": null,
"profile_id": "pro_avq4S1jpyTn6UkRb4hZc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NMxxPseaV1nTfu7vHpR5",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-25T06:03:27.368Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-25T05:48:30.388Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
| [
"crates/router/src/connector/adyen.rs",
"crates/router/src/connector/cybersource/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6012 | Bug: fix: remove internal entity type
We can remove type internal.
TODO:
- Being internal is the property of role and does not depend on entity type
- We can remove logic for internal entity type and transfer it use role.is_internal() wherever it is being used in the code.
- The mini logics like get entity type can be altered it won't take entity type internal to consideration.
Once this is done,
We need to migrate entity type internal in DB to Merchant. | diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a9ece7e9c02..d6f452a5a01 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3144,7 +3144,6 @@ pub enum ApiVersion {
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum EntityType {
- Internal = 3,
Organization = 2,
Merchant = 1,
Profile = 0,
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index 29be4d62aef..71caa41deac 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -33,11 +33,6 @@ impl UserRole {
let org_id = self.org_id.clone()?.get_string_repr().to_string();
Some((org_id, EntityType::Organization))
}
- (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER)
- | (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_ADMIN) => {
- let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string();
- Some((merchant_id, EntityType::Internal))
- }
(enums::UserRoleVersion::V1, _) => {
let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string();
Some((merchant_id, EntityType::Merchant))
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 4c797486970..f36ecc18116 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -650,7 +650,6 @@ async fn handle_existing_user_invitation(
};
let _user_role = match role_info.get_entity_type() {
- EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Merchant => {
user_role
@@ -682,7 +681,6 @@ async fn handle_existing_user_invitation(
{
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let entity = match role_info.get_entity_type() {
- EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Merchant => email_types::Entity {
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
@@ -769,7 +767,6 @@ async fn handle_new_user_invitation(
};
let _user_role = match role_info.get_entity_type() {
- EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Merchant => {
user_role
@@ -805,7 +802,6 @@ async fn handle_new_user_invitation(
let _ = req_state.clone();
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let entity = match role_info.get_entity_type() {
- EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()),
EntityType::Merchant => email_types::Entity {
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
@@ -1089,15 +1085,13 @@ pub async fn create_internal_user(
}
})?;
+ let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id(
+ consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ );
+
let internal_merchant = state
.store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &common_utils::id_type::MerchantId::get_internal_user_merchant_id(
- consts::user_role::INTERNAL_USER_MERCHANT_ID,
- ),
- &key_store,
- )
+ .find_merchant_account_by_merchant_id(key_manager_state, &internal_merchant_id, &key_store)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
@@ -1130,8 +1124,9 @@ pub async fn create_internal_user(
common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
UserStatus::Active,
)
- .add_entity(domain::InternalLevel {
+ .add_entity(domain::MerchantLevel {
org_id: internal_merchant.organization_id,
+ merchant_id: internal_merchant_id,
})
.insert_in_v1_and_v2(&state)
.await
@@ -1443,6 +1438,13 @@ pub async fn list_user_roles_details(
.to_not_found_response(UserErrors::InternalServerError)
.attach_printable("Failed to fetch role info")?;
+ if requestor_role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+
let user_roles_set = state
.store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
@@ -1517,12 +1519,6 @@ pub async fn list_user_roles_details(
merchant.push(merchant_id.clone());
merchant_profile.push((merchant_id, profile_id))
}
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- )
- .into());
- }
EntityType::Organization => (),
};
@@ -1609,11 +1605,6 @@ pub async fn list_user_roles_details(
.ok_or(UserErrors::InternalServerError)?;
let (merchant, profile) = match entity_type {
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- ));
- }
EntityType::Organization => (None, None),
EntityType::Merchant => {
let merchant_id = &user_role
@@ -2623,26 +2614,30 @@ pub async fn list_orgs_for_user(
.await
.change_context(UserErrors::InternalServerError)?;
- let orgs = match role_info.get_entity_type() {
- EntityType::Internal => return Err(UserErrors::InvalidRoleOperation.into()),
- EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
- .store
- .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
- user_id: user_from_token.user_id.as_str(),
- org_id: None,
- merchant_id: None,
- profile_id: None,
- entity_id: None,
- version: None,
- status: Some(UserStatus::Active),
- limit: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|user_role| user_role.org_id)
- .collect::<HashSet<_>>(),
- };
+ if role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+
+ let orgs = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_token.user_id.as_str(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| user_role.org_id)
+ .collect::<HashSet<_>>();
let resp = futures::future::try_join_all(
orgs.iter()
@@ -2676,8 +2671,16 @@ pub async fn list_merchants_for_user_in_org(
)
.await
.change_context(UserErrors::InternalServerError)?;
+
+ if role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+
let merchant_accounts = match role_info.get_entity_type() {
- EntityType::Organization | EntityType::Internal => state
+ EntityType::Organization => state
.store
.list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id)
.await
@@ -2752,7 +2755,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
.await
.change_context(UserErrors::InternalServerError)?;
let profiles = match role_info.get_entity_type() {
- EntityType::Organization | EntityType::Merchant | EntityType::Internal => state
+ EntityType::Organization | EntityType::Merchant => state
.store
.list_profile_by_merchant_id(
key_manager_state,
@@ -2831,7 +2834,7 @@ pub async fn switch_org_for_user(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
- if role_info.get_entity_type() == EntityType::Internal {
+ if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Org switching not allowed for Internal role".to_string(),
)
@@ -2910,126 +2913,54 @@ pub async fn switch_merchant_for_user_in_org(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
- let (org_id, merchant_id, profile_id, role_id) = match role_info.get_entity_type() {
- EntityType::Internal => {
- let merchant_key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .to_not_found_response(UserErrors::MerchantIdNotFound)?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &merchant_key_store,
- )
- .await
- .to_not_found_response(UserErrors::MerchantIdNotFound)?;
-
- let profile_id = state
- .store
- .list_profile_by_merchant_id(
- key_manager_state,
- &merchant_key_store,
- &request.merchant_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list business profiles by merchant_id")?
- .pop()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No business profile found for the given merchant_id")?
- .get_id()
- .to_owned();
-
- (
- merchant_account.organization_id,
- request.merchant_id,
- profile_id,
- user_from_token.role_id.clone(),
+ // Check if the role is internal and handle separately
+ let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
)
- }
-
- EntityType::Organization => {
- let merchant_key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .to_not_found_response(UserErrors::MerchantIdNotFound)?;
-
- let merchant_id = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &merchant_key_store,
- )
- .await
- .change_context(UserErrors::MerchantIdNotFound)?
- .organization_id
- .eq(&user_from_token.org_id)
- .then(|| request.merchant_id.clone())
- .ok_or_else(|| {
- UserErrors::InvalidRoleOperationWithMessage(
- "No such merchant_id found for the user in the org".to_string(),
- )
- })?;
+ .await
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
- let profile_id = state
- .store
- .list_profile_by_merchant_id(key_manager_state, &merchant_key_store, &merchant_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list business profiles by merchant_id")?
- .pop()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No business profile found for the merchant_id")?
- .get_id()
- .to_owned();
- (
- user_from_token.org_id.clone(),
- merchant_id,
- profile_id,
- user_from_token.role_id.clone(),
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &merchant_key_store,
)
- }
-
- EntityType::Merchant | EntityType::Profile => {
- let user_role = state
- .store
- .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
- user_id: &user_from_token.user_id,
- org_id: Some(&user_from_token.org_id),
- merchant_id: Some(&request.merchant_id),
- profile_id: None,
- entity_id: None,
- version: None,
- status: Some(UserStatus::Active),
- limit: Some(1),
- })
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable(
- "Failed to list user roles for the given user_id, org_id and merchant_id",
- )?
- .pop()
- .ok_or(UserErrors::InvalidRoleOperationWithMessage(
- "No user role associated with the requested merchant_id".to_string(),
- ))?;
+ .await
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
- let profile_id = if let Some(profile_id) = &user_role.profile_id {
- profile_id.clone()
- } else {
+ let profile_id = state
+ .store
+ .list_profile_by_merchant_id(
+ key_manager_state,
+ &merchant_key_store,
+ &request.merchant_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to list business profiles by merchant_id")?
+ .pop()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("No business profile found for the given merchant_id")?
+ .get_id()
+ .to_owned();
+
+ (
+ merchant_account.organization_id,
+ request.merchant_id,
+ profile_id,
+ user_from_token.role_id.clone(),
+ )
+ } else {
+ // Match based on the other entity types
+ match role_info.get_entity_type() {
+ EntityType::Organization => {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -3038,31 +2969,82 @@ pub async fn switch_merchant_for_user_in_org(
&state.store.get_master_key().to_vec().into(),
)
.await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
+ .to_not_found_response(UserErrors::MerchantIdNotFound)?;
+
+ let merchant_id = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &request.merchant_id,
+ &merchant_key_store,
+ )
+ .await
+ .change_context(UserErrors::MerchantIdNotFound)?
+ .organization_id
+ .eq(&user_from_token.org_id)
+ .then(|| request.merchant_id.clone())
+ .ok_or_else(|| {
+ UserErrors::InvalidRoleOperationWithMessage(
+ "No such merchant_id found for the user in the org".to_string(),
+ )
+ })?;
- state
+ let profile_id = state
.store
.list_profile_by_merchant_id(
key_manager_state,
&merchant_key_store,
- &request.merchant_id,
+ &merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list business profiles for the given merchant_id")?
+ .attach_printable("Failed to list business profiles by merchant_id")?
.pop()
.ok_or(UserErrors::InternalServerError)
- .attach_printable("No business profile found for the given merchant_id")?
+ .attach_printable("No business profile found for the merchant_id")?
.get_id()
- .to_owned()
- };
- (
- user_from_token.org_id,
- request.merchant_id,
- profile_id,
- user_role.role_id,
- )
+ .to_owned();
+ (
+ user_from_token.org_id.clone(),
+ merchant_id,
+ profile_id,
+ user_from_token.role_id.clone(),
+ )
+ }
+
+ EntityType::Merchant | EntityType::Profile => {
+ let user_role = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &user_from_token.user_id,
+ org_id: Some(&user_from_token.org_id),
+ merchant_id: Some(&request.merchant_id),
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable(
+ "Failed to list user roles for the given user_id, org_id and merchant_id",
+ )?
+ .pop()
+ .ok_or(UserErrors::InvalidRoleOperationWithMessage(
+ "No user role associated with the requested merchant_id".to_string(),
+ ))?;
+
+ let (merchant_id, profile_id) =
+ utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role)
+ .await?;
+ (
+ user_from_token.org_id,
+ merchant_id,
+ profile_id,
+ user_role.role_id,
+ )
+ }
}
};
@@ -3116,7 +3098,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
.attach_printable("Failed to retrieve role information")?;
let (profile_id, role_id) = match role_info.get_entity_type() {
- EntityType::Internal | EntityType::Organization | EntityType::Merchant => {
+ EntityType::Organization | EntityType::Merchant => {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index fd9c8c89031..b841f88eca1 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -734,7 +734,6 @@ pub async fn list_users_in_lineage(
)
.await?
}
- EntityType::Internal => HashSet::new(),
};
let mut email_map = state
@@ -859,10 +858,13 @@ pub async fn list_invitations_for_user(
.clone()
.ok_or(UserErrors::InternalServerError)?,
)),
- EntityType::Internal => return Err(report!(UserErrors::InternalServerError)),
}
- Ok((org_ids, merchant_ids, profile_ids_with_merchant_ids))
+ Ok::<_, error_stack::Report<UserErrors>>((
+ org_ids,
+ merchant_ids,
+ profile_ids_with_merchant_ids,
+ ))
},
)?;
@@ -953,7 +955,6 @@ pub async fn list_invitations_for_user(
.as_ref()
.map(|profile_id| profile_name_map.get(profile_id).cloned())
.ok_or(UserErrors::InternalServerError)?,
- EntityType::Internal => return Err(report!(UserErrors::InternalServerError)),
};
Ok(user_role_api::ListInvitationForUserResponse {
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index ffc18214c20..d5d655b4a89 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -224,6 +224,13 @@ pub async fn list_roles_with_info(
.await
.attach_printable("Invalid role_id in JWT")?;
+ if user_role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+
let mut role_info_vec = PREDEFINED_ROLES
.iter()
.map(|(_, role_info)| role_info.clone())
@@ -256,12 +263,6 @@ pub async fn list_roles_with_info(
.attach_printable("Failed to get roles")?,
// TODO: Populate this from Db function when support for profile id and profile level custom roles is added
EntityType::Profile => Vec::new(),
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- )
- .into());
- }
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
@@ -336,13 +337,6 @@ pub async fn list_roles_at_entity_level(
.attach_printable("Failed to get roles")?,
// TODO: Populate this from Db function when support for profile id and profile level custom roles is added
EntityType::Profile => Vec::new(),
-
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- )
- .into());
- }
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index df42d412989..b271abd1eff 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -31,7 +31,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
- entity_type: EntityType::Internal,
+ entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
@@ -52,7 +52,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
- entity_type: EntityType::Internal,
+ entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 725cefb8c41..19d682aeef1 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1136,11 +1136,6 @@ pub struct ProfileLevel {
pub profile_id: id_type::ProfileId,
}
-#[derive(Clone)]
-pub struct InternalLevel {
- pub org_id: id_type::OrganizationId,
-}
-
#[derive(Clone)]
pub struct NewUserRole<E: Clone> {
pub user_id: String,
@@ -1316,29 +1311,6 @@ impl NewUserRole<MerchantLevel> {
}
}
-impl NewUserRole<InternalLevel> {
- pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> {
- let entity = self.entity.clone();
- let internal_merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
- consts::user_role::INTERNAL_USER_MERCHANT_ID,
- );
-
- let new_v1_role = self
- .clone()
- .convert_to_new_v1_role(entity.org_id.clone(), internal_merchant_id.clone());
-
- let new_v2_role = self.convert_to_new_v2_role(EntityInfo {
- org_id: entity.org_id.clone(),
- merchant_id: Some(internal_merchant_id.clone()),
- profile_id: None,
- entity_id: internal_merchant_id.get_string_repr().to_owned(),
- entity_type: EntityType::Internal,
- });
-
- Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
- }
-}
-
impl NewUserRole<ProfileLevel> {
pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> {
let entity = self.entity.clone();
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 9141b91bdd6..f2aae68fcbc 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -239,10 +239,7 @@ pub async fn get_single_merchant_id(
.attach_printable("No merchants found for org_id")?
.get_id()
.clone()),
- Some(EntityType::Merchant)
- | Some(EntityType::Internal)
- | Some(EntityType::Profile)
- | None => user_role
+ Some(EntityType::Merchant) | Some(EntityType::Profile) | None => user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)
@@ -263,9 +260,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
)>,
> {
match entity_type {
- EntityType::Internal | EntityType::Organization => {
- Err(UserErrors::InvalidRoleOperation.into())
- }
+ EntityType::Organization => Err(UserErrors::InvalidRoleOperation.into()),
EntityType::Merchant => {
let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else {
return Ok(None);
@@ -369,7 +364,7 @@ pub async fn get_single_merchant_id_and_profile_id(
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
let profile_id = match entity_type {
- EntityType::Organization | EntityType::Merchant | EntityType::Internal => {
+ EntityType::Organization | EntityType::Merchant => {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -438,14 +433,6 @@ pub fn get_min_entity(
| (EntityType::Merchant, Some(EntityType::Profile))
| (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile),
- (EntityType::Internal, _) => Ok(EntityType::Internal),
-
- (EntityType::Organization, Some(EntityType::Internal))
- | (EntityType::Merchant, Some(EntityType::Internal))
- | (EntityType::Profile, Some(EntityType::Internal)) => {
- Err(UserErrors::InvalidRoleOperation.into())
- }
-
(EntityType::Merchant, Some(EntityType::Organization))
| (EntityType::Profile, Some(EntityType::Organization))
| (EntityType::Profile, Some(EntityType::Merchant)) => {
diff --git a/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql
new file mode 100644
index 00000000000..7d206b424e1
--- /dev/null
+++ b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+UPDATE user_roles SET entity_type = 'internal' where role_id like 'internal%' and version = 'v2';
diff --git a/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql
new file mode 100644
index 00000000000..4fc5ea7d314
--- /dev/null
+++ b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+UPDATE user_roles SET entity_type = 'merchant' WHERE entity_type = 'internal';
\ No newline at end of file
| 2024-09-24T11:18:33Z |
## Description
Remove internal from entity type. Being internal is the property of role and does not depend on entity type. Even internal role can have the entity types as 'Merchant', 'Org' or '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
Closes [#6012](https://github.com/juspay/hyperswitch/issues/6012)
## How did you test it?
Switch should work fine for users
For internal users also switch merchant should work as expected.
```
curl --location 'http://localhost:8080/user/switch/merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_id": "some_merchant_id"
}'
```
The response will give new token after switch
```
{
"token": JWT,
"token_type": "user_info"
}
``` | 3ddfe53838c6b039dc5f669ccd23d3035521d691 | Switch should work fine for users
For internal users also switch merchant should work as expected.
```
curl --location 'http://localhost:8080/user/switch/merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_id": "some_merchant_id"
}'
```
The response will give new token after switch
```
{
"token": JWT,
"token_type": "user_info"
}
```
| [
"crates/common_enums/src/enums.rs",
"crates/diesel_models/src/user_role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/services/authorization/roles/predefined_roles.rs",
"crates/router/src/types/domain/user.rs"... | |
juspay/hyperswitch | juspay__hyperswitch-6004 | Bug: [BUG] [CORE] Payment method details are being none in Psync Response.
### Bug Description
Payment method details are being none in Psync Response.
### Expected Behavior
Payment method data should be populated in Psync response for all the payment methods, except for network token.
### Actual Behavior
Payment method details are being none in Psync Response for all the payment methods.
### Steps To Reproduce
Make a payment.
Sync the response and check for payment method data
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 37e178dc7f3..d8c5f88dde9 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -784,36 +784,16 @@ where
.map(ToString::to_string)
.unwrap_or("".to_owned());
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
- match payment_data.get_payment_method_data(){
- Some(payment_method_data) => match payment_method_data{
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardRedirect(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::PayLater(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankTransfer(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Crypto(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::RealTimePayment(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::Voucher(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::GiftCard(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardToken(_) |
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::OpenBanking(_) => {payment_attempt
- .payment_method_data
- .clone()
- .map(|data| data.parse_value("payment_method_data"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_method_data",
- })?},
- hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => None,
- }
- None => None
-
- };
+ payment_attempt
+ .payment_method_data
+ .clone()
+ .and_then(|data| match data {
+ serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
+ _ => Some(data.parse_value("AdditionalPaymentData")),
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?;
let surcharge_details =
payment_attempt
| 2024-09-24T08:35:45Z |
## Description
<!-- Describe your changes in detail -->
Currently, in Psync response, payment_method_data is being none. Updated the Psync response with pm data.
For network token pm data will be none, since we are not storing additional pm data in attempt.
For other payment methods, it will continue to function as it did previously.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
payment curl -
```{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com/",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "stripe"
}
}
```
test cases - make a successful payment, pm data should be displayed in the response
PaymentsCreate -
<img width="702" alt="Screenshot 2024-09-24 at 1 54 01 PM" src="https://github.com/user-attachments/assets/cb4635ef-95c9-4127-aa67-25f1b372efd3">
PSync -
<img width="710" alt="Screenshot 2024-09-24 at 1 54 16 PM" src="https://github.com/user-attachments/assets/1fb845e8-da1a-4257-af73-0cdce5171d56">
Save Card flow -
<img width="763" alt="Screenshot 2024-09-24 at 1 54 30 PM" src="https://github.com/user-attachments/assets/2c2dde1c-f841-47b5-9d76-a4fcd48d5204">
payment create - wallet - googlepay
<img width="994" alt="Screenshot 2024-09-24 at 5 26 55 PM" src="https://github.com/user-attachments/assets/5bb6671b-3758-4d06-8d01-1a344efff518">
sync response - wallet
<img width="896" alt="Screenshot 2024-09-24 at 5 28 48 PM" src="https://github.com/user-attachments/assets/643f82c8-3915-4e7b-b807-ec63ec12435d">
confirm - network token
<img width="752" alt="Screenshot 2024-09-24 at 5 31 01 PM" src="https://github.com/user-attachments/assets/156d2f2c-4728-445e-b046-58ae7790c1dc"> | 8a9fed36fc7f01f54d9a2e725abf459fac857222 |
payment curl -
```{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com/",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "stripe"
}
}
```
test cases - make a successful payment, pm data should be displayed in the response
PaymentsCreate -
<img width="702" alt="Screenshot 2024-09-24 at 1 54 01 PM" src="https://github.com/user-attachments/assets/cb4635ef-95c9-4127-aa67-25f1b372efd3">
PSync -
<img width="710" alt="Screenshot 2024-09-24 at 1 54 16 PM" src="https://github.com/user-attachments/assets/1fb845e8-da1a-4257-af73-0cdce5171d56">
Save Card flow -
<img width="763" alt="Screenshot 2024-09-24 at 1 54 30 PM" src="https://github.com/user-attachments/assets/2c2dde1c-f841-47b5-9d76-a4fcd48d5204">
payment create - wallet - googlepay
<img width="994" alt="Screenshot 2024-09-24 at 5 26 55 PM" src="https://github.com/user-attachments/assets/5bb6671b-3758-4d06-8d01-1a344efff518">
sync response - wallet
<img width="896" alt="Screenshot 2024-09-24 at 5 28 48 PM" src="https://github.com/user-attachments/assets/643f82c8-3915-4e7b-b807-ec63ec12435d">
confirm - network token
<img width="752" alt="Screenshot 2024-09-24 at 5 31 01 PM" src="https://github.com/user-attachments/assets/156d2f2c-4728-445e-b046-58ae7790c1dc">
| [
"crates/router/src/core/payments/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5966 | Bug: [BUG] Bug in merchant connector account create - delete flows
### Bug Description
There is a problem with how the `configs` table is updated. The problem arises when a user deletes a connector and then adds the same one, the config isn't cleaned from the connector when it's deleted, and the new connector (with the same type) is appended to the array.
It looks something like this:
```json
[{"connector":"adyen","merchant_connector_id":"mca_123XXX"}, //old one, already deleted
{"connector":"adyen","merchant_connector_id":"mca_456XXX"}] //new one
```
When a payment (or payout or anything else connector related) is being created the router looks at the first occurrence of the connector (which is already deleted) and then looks at the `merchant_connector_account` table for an already deleted `merchant_connector_id`, unsurprisingly does not find it and throws an error. Affects both payment and payout processors
### Expected Behavior
I think either the payment connector delete function should clean the config array of the deleted connector, or the update function should prepend the config instead of appending.
### Actual Behavior
The delete function does not clean the config and then just appends it when new creator of same type is added
### Steps To Reproduce
To reproduce:
1. Create a merchant connector account of any type
2. Delete it
3. Create the same connector
4. Try to make a payment with that connector
5. Get error 404:
```json
{
"error": {
"type": "invalid_request",
"message": "Merchant connector account does not exist in our records",
"code": "HE_02",
"reason": "mca_123XXX does not exist"
}
}
```
### Context For The Bug
Trace for update config:
```sh
at crates/diesel_models/src/query/generics.rs:247
in router::db::configs::update_config_in_database
in storage_impl::redis::cache::publish_and_redact
in router::db::configs::update_config_by_key
in core::routing::helpers::update_merchant_default_config
in router::core::retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists
```
### Environment
Are you using hyperswitch hosted version? No
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution: Ubuntu 22.04
2. Rust version (output of `rustc --version`): `rustc 1.80.1 (3f5fd8dd4 2024-08-06)`
3. App version (output of `cargo r --features vergen -- --version`): `2024.08.27` (not running the latest version but checked the functions responsible and there weren't any changes)
### 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/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 781b5e3710a..f0adf49c1e8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3327,6 +3327,16 @@ pub enum PresenceOfCustomerDuringPayment {
Absent,
}
+impl From<ConnectorType> for TransactionType {
+ fn from(connector_type: ConnectorType) -> Self {
+ match connector_type {
+ #[cfg(feature = "payouts")]
+ ConnectorType::PayoutProcessor => Self::Payout,
+ _ => Self::Payment,
+ }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)]
pub enum TaxCalculationOverride {
/// Skip calling the external tax provider
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 055c428b1fb..26a3be0863c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1931,6 +1931,65 @@ impl<'a> MerchantDefaultConfigUpdate<'a> {
}
Ok(())
}
+
+ async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let mut default_routing_config = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.merchant_id.get_string_repr(),
+ self.transaction_type,
+ )
+ .await?;
+
+ let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
+ self.store,
+ self.profile_id.get_string_repr(),
+ self.transaction_type,
+ )
+ .await?;
+
+ if let Some(routable_connector_val) = self.routable_connector {
+ let choice = routing_types::RoutableConnectorChoice {
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: *routable_connector_val,
+ merchant_connector_id: Some(self.merchant_connector_id.clone()),
+ };
+ if default_routing_config.contains(&choice) {
+ default_routing_config.retain(|mca| {
+ mca.merchant_connector_id
+ .as_ref()
+ .map_or(true, |merchant_connector_id| {
+ merchant_connector_id != self.merchant_connector_id
+ })
+ });
+ routing::helpers::update_merchant_default_config(
+ self.store,
+ self.merchant_id.get_string_repr(),
+ default_routing_config.clone(),
+ self.transaction_type,
+ )
+ .await?;
+ }
+ if default_routing_config_for_profile.contains(&choice.clone()) {
+ default_routing_config_for_profile.retain(|mca| {
+ mca.merchant_connector_id
+ .as_ref()
+ .map_or(true, |merchant_connector_id| {
+ merchant_connector_id != self.merchant_connector_id
+ })
+ });
+ routing::helpers::update_merchant_default_config(
+ self.store,
+ self.profile_id.get_string_repr(),
+ default_routing_config_for_profile.clone(),
+ self.transaction_type,
+ )
+ .await?;
+ }
+ }
+ Ok(())
+ }
}
#[cfg(feature = "v2")]
struct DefaultFallbackRoutingConfigUpdate<'a> {
@@ -1970,6 +2029,40 @@ impl<'a> DefaultFallbackRoutingConfigUpdate<'a> {
}
Ok(())
}
+
+ async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
+ &self,
+ ) -> RouterResult<()> {
+ let profile_wrapper = ProfileWrapper::new(self.business_profile.clone());
+ let default_routing_config_for_profile =
+ &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
+ if let Some(routable_connector_val) = self.routable_connector {
+ let choice = routing_types::RoutableConnectorChoice {
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: *routable_connector_val,
+ merchant_connector_id: Some(self.merchant_connector_id.clone()),
+ };
+ if default_routing_config_for_profile.contains(&choice.clone()) {
+ default_routing_config_for_profile.retain(|mca| {
+ mca.merchant_connector_id
+ .as_ref()
+ .map_or(true, |merchant_connector_id| {
+ merchant_connector_id != self.merchant_connector_id
+ })
+ });
+
+ profile_wrapper
+ .update_default_fallback_routing_of_connectors_under_profile(
+ self.store,
+ default_routing_config_for_profile,
+ self.key_manager_state,
+ &self.key_store,
+ )
+ .await?
+ }
+ }
+ Ok(())
+ }
}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
@@ -3139,7 +3232,7 @@ pub async fn delete_connector(
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
- let _mca = db
+ let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
@@ -3161,6 +3254,26 @@ pub async fn delete_connector(
id: merchant_connector_id.get_string_repr().to_string(),
})?;
+ // delete the mca from the config as well
+ let merchant_default_config_delete = MerchantDefaultConfigUpdate {
+ routable_connector: &Some(
+ common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector_name",
+ }
+ })?,
+ ),
+ merchant_connector_id: &mca.get_id(),
+ store: db,
+ merchant_id: &merchant_id,
+ profile_id: &mca.profile_id,
+ transaction_type: &mca.connector_type.into(),
+ };
+
+ merchant_default_config_delete
+ .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
+ .await?;
+
let response = api::MerchantConnectorDeleteResponse {
merchant_id,
merchant_connector_id,
@@ -3207,6 +3320,32 @@ pub async fn delete_connector(
id: id.clone().get_string_repr().to_string(),
})?;
+ let business_profile = db
+ .find_business_profile_by_profile_id(key_manager_state, &key_store, &mca.profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
+ id: mca.profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate {
+ routable_connector: &Some(
+ common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector_name",
+ }
+ })?,
+ ),
+ merchant_connector_id: &mca.get_id(),
+ store: db,
+ business_profile,
+ key_store,
+ key_manager_state,
+ };
+
+ merchant_default_config_delete
+ .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
+ .await?;
+
let response = api::MerchantConnectorDeleteResponse {
merchant_id: merchant_id.clone(),
id,
| 2024-09-23T13:34:14Z |
## Description
Fixes #5966 (in both v1 and v2). Now the router cleans up the configs table (or business_profile in v2) when a connector 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?
Added a payment and payout processor, checked if values are present in config, deleted and rechecked.
v1:

v2:

## Test on Integ
- Create any 2 MCA's
```
curl --location 'http://localhost:8080/account/merchant_1733401776/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "stripe",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "{{api_key}}"
},
"connector_label": "stripe_US_default7777",
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa"
],
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "debit",
"card_networks": [
"JCB"
],
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"minimum_amount": 600,
"maximum_amount": 800,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"card_networks": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
}
],
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```
- Do the list for default fallback routing connectors, the connector should be present
```
curl --location 'http://localhost:8080/routing/default/profile' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \
--data ''
```
- Delete the one of those 2 MCA's
```
curl --location --request DELETE 'http://localhost:8080/account/merchant_1733401776/connectors/mca_jIEg3gZxzs54aMMrhT9D' \
--header 'Accept: application/json' \
--header 'api-key: test_admin'
```
- The list for default fallback routing connectors, the connector shouldn't be present
```
curl --location 'http://localhost:8080/routing/default/profile' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \
--data ''
``` | 64383915bda5693df1cecf6cc5683e8b9aaef99b | Added a payment and payout processor, checked if values are present in config, deleted and rechecked.
v1:

v2:

| [
"crates/common_enums/src/enums.rs",
"crates/router/src/core/admin.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5996 | Bug: feat(users): Add entity type filter in list users and list roles API
Currently list users and list roles API is sending all the users and roles respectively for those who are same entity level and less.
We need to add filters in these APIs to send users and roles who are only at particular entity level. | diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 81b38198cfc..eb09abd471c 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,12 +2,12 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesResponse,
- RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
- UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest,
+ ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse,
+ RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- MerchantSelectRequest, UpdateUserRoleRequest,
+ ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
@@ -25,6 +25,8 @@ common_utils::impl_api_event_type!(
ListRolesResponse,
ListRolesAtEntityLevelRequest,
RoleInfoResponseNew,
- RoleInfoWithGroupsResponse
+ RoleInfoWithGroupsResponse,
+ ListUsersInEntityRequest,
+ ListRolesRequest
)
);
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 8e1a0483c07..f2743d6a311 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -159,3 +159,8 @@ pub struct Entity {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListUsersInEntityRequest {
+ pub entity_type: Option<common_enums::EntityType>,
+}
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 828dfeb20f8..be467421e65 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -35,6 +35,11 @@ pub struct RoleInfoWithGroupsResponse {
pub role_scope: RoleScope,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListRolesRequest {
+ pub entity_type: Option<EntityType>,
+}
+
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseNew {
pub role_id: String,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index d42f71695a5..fd9c8c89031 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -673,6 +673,7 @@ pub async fn delete_user_role(
pub async fn list_users_in_lineage(
state: SessionState,
user_from_token: auth::UserFromToken,
+ request: user_role_api::ListUsersInEntityRequest,
) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> {
let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
@@ -683,51 +684,55 @@ pub async fn list_users_in_lineage(
.await
.change_context(UserErrors::InternalServerError)?;
- let user_roles_set: HashSet<_> = match requestor_role_info.get_entity_type() {
- EntityType::Organization => state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
- user_id: None,
- org_id: &user_from_token.org_id,
- merchant_id: None,
- profile_id: None,
- version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect(),
- EntityType::Merchant => state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
- user_id: None,
- org_id: &user_from_token.org_id,
- merchant_id: Some(&user_from_token.merchant_id),
- profile_id: None,
- version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect(),
+ let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity(
+ requestor_role_info.get_entity_type(),
+ request.entity_type,
+ )? {
+ EntityType::Organization => {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: None,
+ profile_id: None,
+ version: None,
+ },
+ request.entity_type,
+ )
+ .await?
+ }
+ EntityType::Merchant => {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id: None,
+ version: None,
+ },
+ request.entity_type,
+ )
+ .await?
+ }
EntityType::Profile => {
let Some(profile_id) = user_from_token.profile_id.as_ref() else {
return Err(UserErrors::JwtProfileIdMissing.into());
};
- state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
user_id: None,
org_id: &user_from_token.org_id,
merchant_id: Some(&user_from_token.merchant_id),
profile_id: Some(profile_id),
version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect()
+ },
+ request.entity_type,
+ )
+ .await?
}
EntityType::Internal => HashSet::new(),
};
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 571ae7f995d..ffc18214c20 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -217,6 +217,7 @@ pub async fn update_role(
pub async fn list_roles_with_info(
state: SessionState,
user_from_token: UserFromToken,
+ request: role_api::ListRolesRequest,
) -> UserResponse<Vec<role_api::RoleInfoResponseNew>> {
let user_role_info = user_from_token
.get_role_info_from_db(&state)
@@ -229,49 +230,57 @@ pub async fn list_roles_with_info(
.collect::<Vec<_>>();
let user_role_entity = user_role_info.get_entity_type();
- let custom_roles = match user_role_entity {
- EntityType::Organization => state
- .store
- .list_roles_for_org_by_parameters(&user_from_token.org_id, None, None, None)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to get roles")?,
- EntityType::Merchant => state
- .store
- .list_roles_for_org_by_parameters(
- &user_from_token.org_id,
- Some(&user_from_token.merchant_id),
- None,
- None,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to get roles")?,
- // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
- EntityType::Profile => Vec::new(),
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- )
- .into());
- }
- };
+ let custom_roles =
+ match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? {
+ EntityType::Organization => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ None,
+ request.entity_type,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ EntityType::Merchant => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ Some(&user_from_token.merchant_id),
+ request.entity_type,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
+ EntityType::Profile => Vec::new(),
+ EntityType::Internal => {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+ };
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
+
let list_role_info_response = role_info_vec
.into_iter()
.filter_map(|role_info| {
- if user_role_entity >= role_info.get_entity_type() {
- Some(role_api::RoleInfoResponseNew {
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- groups: role_info.get_permission_groups().to_vec(),
- entity_type: role_info.get_entity_type(),
- scope: role_info.get_scope(),
- })
- } else {
- None
- }
+ let is_lower_entity = user_role_entity >= role_info.get_entity_type();
+ let request_filter = request.entity_type.map_or(true, |entity_type| {
+ entity_type == role_info.get_entity_type()
+ });
+
+ (is_lower_entity && request_filter).then_some(role_api::RoleInfoResponseNew {
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ groups: role_info.get_permission_groups().to_vec(),
+ entity_type: role_info.get_entity_type(),
+ scope: role_info.get_scope(),
+ })
})
.collect::<Vec<_>>();
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index b1260b5d7ad..922e7612b14 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -291,16 +291,20 @@ pub async fn get_role_information(
.await
}
-pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn list_users_in_lineage(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<user_role_api::ListUsersInEntityRequest>,
+) -> HttpResponse {
let flow = Flow::ListUsersInLineage;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
- (),
- |state, user_from_token, _, _| {
- user_role_core::list_users_in_lineage(state, user_from_token)
+ query.into_inner(),
+ |state, user_from_token, request, _| {
+ user_role_core::list_users_in_lineage(state, user_from_token, request)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
@@ -308,15 +312,21 @@ pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest)
.await
}
-pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn list_roles_with_info(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<role_api::ListRolesRequest>,
+) -> HttpResponse {
let flow = Flow::ListRolesV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
- (),
- |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token),
+ query.into_inner(),
+ |state, user_from_token, request, _| {
+ role_core::list_roles_with_info(state, user_from_token, request)
+ },
&auth::JWTAuth {
permission: Permission::UsersRead,
minimum_entity_level: EntityType::Profile,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index b4008bd0008..9141b91bdd6 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -14,7 +14,7 @@ use storage_impl::errors::StorageError;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
- db::user_role::ListUserRolesByUserIdPayload,
+ db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
routes::SessionState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -398,3 +398,61 @@ pub async fn get_single_merchant_id_and_profile_id(
Ok((merchant_id, profile_id))
}
+
+pub async fn fetch_user_roles_by_payload(
+ state: &SessionState,
+ payload: ListUserRolesByOrgIdPayload<'_>,
+ request_entity_type: Option<EntityType>,
+) -> UserResult<HashSet<UserRole>> {
+ Ok(state
+ .store
+ .list_user_roles_by_org_id(payload)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| {
+ let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
+ request_entity_type
+ .map_or(true, |req_entity_type| entity_type == req_entity_type)
+ .then_some(user_role)
+ })
+ .collect::<HashSet<_>>())
+}
+
+pub fn get_min_entity(
+ user_entity: EntityType,
+ filter_entity: Option<EntityType>,
+) -> UserResult<EntityType> {
+ match (user_entity, filter_entity) {
+ (EntityType::Organization, None)
+ | (EntityType::Organization, Some(EntityType::Organization)) => {
+ Ok(EntityType::Organization)
+ }
+
+ (EntityType::Merchant, None)
+ | (EntityType::Organization, Some(EntityType::Merchant))
+ | (EntityType::Merchant, Some(EntityType::Merchant)) => Ok(EntityType::Merchant),
+
+ (EntityType::Profile, None)
+ | (EntityType::Organization, Some(EntityType::Profile))
+ | (EntityType::Merchant, Some(EntityType::Profile))
+ | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile),
+
+ (EntityType::Internal, _) => Ok(EntityType::Internal),
+
+ (EntityType::Organization, Some(EntityType::Internal))
+ | (EntityType::Merchant, Some(EntityType::Internal))
+ | (EntityType::Profile, Some(EntityType::Internal)) => {
+ Err(UserErrors::InvalidRoleOperation.into())
+ }
+
+ (EntityType::Merchant, Some(EntityType::Organization))
+ | (EntityType::Profile, Some(EntityType::Organization))
+ | (EntityType::Profile, Some(EntityType::Merchant)) => {
+ Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "{} level user requesting data for {:?} level",
+ user_entity, filter_entity
+ ))
+ }
+ }
+}
| 2024-09-23T13:30:11Z |
## Description
<!-- Describe your changes in detail -->
- Adds entity_type filter in list users and list roles API.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5996.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. List Users
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
This should respond with all the users who are at the same level and lower.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=organization' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by org level users and only responds with org level users.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=merchant' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by merchant and org level users and only responds with merchant level users.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=profile' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by profile, merchant and org level users and only responds with profile level users.
Response for all the above curls should follow the same structure
```json
[
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
}
]
```
2. List Roles
```
curl 'http://localhost:8080/user/role/v2/list' \
-H 'authorization: Bearer JWT''
```
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=merchant' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org and merchant level users and only responds with merchant level roles.
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=profile' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org, merchant and profile level users and only responds with profile level roles.
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=organization' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org level users and only responds with org level roles.
Response should look like this:
```json
[
{
"role_id": "merchant_iam_admin",
"role_name": "merchant_iam",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_developer",
"role_name": "merchant_developer",
"entity_type": "merchant",
"groups": [
"operations_view",
"connectors_view",
"analytics_view",
"users_view",
"merchant_details_view",
"merchant_details_manage"
],
"scope": "organization"
},
{
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "profile_customer_support",
"role_name": "profile_customer_support",
"entity_type": "profile",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_admin",
"role_name": "merchant_admin",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage",
"recon_ops"
],
"scope": "organization"
},
{
"role_id": "merchant_operator",
"role_name": "merchant_operator",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "profile_operator",
"role_name": "profile_operator",
"entity_type": "profile",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "org_admin",
"role_name": "organization_admin",
"entity_type": "organization",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage",
"organization_manage",
"recon_ops"
],
"scope": "organization"
}
]
``` | 035906e9b1b1a1e52fe970db5d7e028556fa82b4 |
1. List Users
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
This should respond with all the users who are at the same level and lower.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=organization' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by org level users and only responds with org level users.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=merchant' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by merchant and org level users and only responds with merchant level users.
```
curl 'http://localhost:8080/user/user/v2/list?entity_type=profile' \
-H 'authorization: Bearer JWT' \
```
This can only be hit by profile, merchant and org level users and only responds with profile level users.
Response for all the above curls should follow the same structure
```json
[
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
},
{
"email": "email",
"roles": [
{
"role_id": "merchant_view_only",
"role_name": "merchant_view_only"
}
]
}
]
```
2. List Roles
```
curl 'http://localhost:8080/user/role/v2/list' \
-H 'authorization: Bearer JWT''
```
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=merchant' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org and merchant level users and only responds with merchant level roles.
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=profile' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org, merchant and profile level users and only responds with profile level roles.
```
curl 'http://localhost:8080/user/role/v2/list?entity_type=organization' \
-H 'authorization: Bearer JWT''
```
This can only be hit by org level users and only responds with org level roles.
Response should look like this:
```json
[
{
"role_id": "merchant_iam_admin",
"role_name": "merchant_iam",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_developer",
"role_name": "merchant_developer",
"entity_type": "merchant",
"groups": [
"operations_view",
"connectors_view",
"analytics_view",
"users_view",
"merchant_details_view",
"merchant_details_manage"
],
"scope": "organization"
},
{
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"entity_type": "merchant",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "profile_customer_support",
"role_name": "profile_customer_support",
"entity_type": "profile",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "merchant_admin",
"role_name": "merchant_admin",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage",
"recon_ops"
],
"scope": "organization"
},
{
"role_id": "merchant_operator",
"role_name": "merchant_operator",
"entity_type": "merchant",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "profile_operator",
"role_name": "profile_operator",
"entity_type": "profile",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"scope": "organization"
},
{
"role_id": "org_admin",
"role_name": "organization_admin",
"entity_type": "organization",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage",
"organization_manage",
"recon_ops"
],
"scope": "organization"
}
]
```
| [
"crates/api_models/src/events/user_role.rs",
"crates/api_models/src/user_role.rs",
"crates/api_models/src/user_role/role.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/routes/user_role.rs",
"crates/router/src/utils/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5995 | Bug: feat(payments): support for card_network filter in payments list
- Support for card_network as filters in payments list
- Card network values in payments filter values | diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 584f81992bd..4034b8cd58e 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4361,6 +4361,8 @@ pub struct PaymentListFilterConstraints {
/// The order in which payments list should be sorted
#[serde(default)]
pub order: Order,
+ /// The List of all the card networks to filter payments list
+ pub card_network: Option<Vec<enums::CardNetwork>>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFilters {
@@ -4390,6 +4392,8 @@ pub struct PaymentListFiltersV2 {
pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>,
/// The list of available authentication types
pub authentication_type: Vec<enums::AuthenticationType>,
+ /// The list of available card networks
+ pub card_network: Vec<enums::CardNetwork>,
}
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 562e5d205c0..be2b3547110 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1294,6 +1294,7 @@ pub struct PaymentIntentListParams {
pub ending_before_id: Option<id_type::PaymentId>,
pub limit: Option<u32>,
pub order: api_models::payments::Order,
+ pub card_network: Option<Vec<storage_enums::CardNetwork>>,
}
impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints {
@@ -1327,6 +1328,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
ending_before_id: ending_before,
limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
order: Default::default(),
+ card_network: None,
}))
}
}
@@ -1351,6 +1353,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
ending_before_id: None,
limit: None,
order: Default::default(),
+ card_network: None,
}))
}
}
@@ -1373,6 +1376,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
authentication_type,
merchant_connector_id,
order,
+ card_network,
} = value;
if let Some(payment_intent_id) = payment_id {
Self::Single { payment_intent_id }
@@ -1395,6 +1399,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF
ending_before_id: None,
limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)),
order,
+ card_network,
}))
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index d7899e8b9a9..859796310f0 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3380,6 +3380,7 @@ pub async fn get_payment_filters(
status: enums::IntentStatus::iter().collect(),
payment_method: payment_method_types_map,
authentication_type: enums::AuthenticationType::iter().collect(),
+ card_network: enums::CardNetwork::iter().collect(),
},
))
}
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 4c7232f6f3f..f5c3deeb18c 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -939,6 +939,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
None => query,
};
+ if let Some(card_network) = ¶ms.card_network {
+ query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
+ }
query
}
};
| 2024-09-23T09:15:45Z |
## Description
<!-- Describe your changes in detail -->
- Support for card_network as filters in payments list
- Card network values in payments filter values
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5995
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Payments filter list
Request
```
curl --location 'http://localhost:8080/payments/v2/filter' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"connector": {
"connector_name": [
{
"connector_label": "connector_label",
"merchant_connector_id": "connector_id"
}
]
},
"currency": [Array of currency values],
"status": [Array of status],
"payment_method": { [Array of payment methods]},
"authentication_type": [Array of authentication types],
"card_network": [
"Visa",
"Mastercard",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay",
"Interac",
"RuPay",
"Maestro"
]
}
```
2. Payments list with filter
Request
```
curl --location 'http://localhost:8080/payments/list' \
--header 'authorization: Bearer JWT "
--data '{"offset":0,"limit":50,"start_time":"2024-08-23T18:30:00Z","card_network":["Visa"]}'
```
Response
```
{
"count": 2,
"total_count": 2,
"data": [
{
"payment_id": "pay_TTYRZZpn4GZgyZkvfpLz",
"merchant_id": "merchant_1726749985",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "pay_TTYRZZpn4GZgyZkvfpLz_secret_BNl87WI1lhH3h92QwwRi",
"created": "2024-09-23T06:52:14.730Z",
"currency": "USD",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Default value",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": null,
"card_type": null,
"card_network": "Visa",
"card_issuer": "",
"card_issuing_country": null,
"card_isin": null,
"card_extended_bin": null,
"card_exp_month": null,
"card_exp_year": null,
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "billing_email@gmail.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "pay_2dJSM6oUYFoKtxtD45jm",
"frm_message": null,
"metadata": {
"order_details": {
"amount": 10000,
"quantity": 1,
"product_name": "Apple iphone 15"
}
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ClRdOxbia1VPXGEvFHe3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_fBms1u3jKBroyqKUax5S",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
},
{
"payment_id": "pay_8rF6jCw4J0W4e2eV7WqC",
"merchant_id": "merchant_1726749985",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 10000,
"amount_received": null,
"connector": null,
"client_secret": "pay_8rF6jCw4J0W4e2eV7WqC_secret_LuwsymB20YhQ1MaujKgK",
"created": "2024-09-23T06:50:09.337Z",
"currency": "USD",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Default value",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": {
"card": {
"last4": null,
"card_type": null,
"card_network": "Visa",
"card_issuer": "",
"card_issuing_country": null,
"card_isin": null,
"card_extended_bin": null,
"card_exp_month": null,
"card_exp_year": null,
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "billing_email@gmail.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"order_details": {
"amount": 10000,
"quantity": 1,
"product_name": "Apple iphone 15"
}
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ClRdOxbia1VPXGEvFHe3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
]
}
``` | b7139483bb4735b7dfaf7e659ab33a16a90af1db |
1. Payments filter list
Request
```
curl --location 'http://localhost:8080/payments/v2/filter' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"connector": {
"connector_name": [
{
"connector_label": "connector_label",
"merchant_connector_id": "connector_id"
}
]
},
"currency": [Array of currency values],
"status": [Array of status],
"payment_method": { [Array of payment methods]},
"authentication_type": [Array of authentication types],
"card_network": [
"Visa",
"Mastercard",
"AmericanExpress",
"JCB",
"DinersClub",
"Discover",
"CartesBancaires",
"UnionPay",
"Interac",
"RuPay",
"Maestro"
]
}
```
2. Payments list with filter
Request
```
curl --location 'http://localhost:8080/payments/list' \
--header 'authorization: Bearer JWT "
--data '{"offset":0,"limit":50,"start_time":"2024-08-23T18:30:00Z","card_network":["Visa"]}'
```
Response
```
{
"count": 2,
"total_count": 2,
"data": [
{
"payment_id": "pay_TTYRZZpn4GZgyZkvfpLz",
"merchant_id": "merchant_1726749985",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "pay_TTYRZZpn4GZgyZkvfpLz_secret_BNl87WI1lhH3h92QwwRi",
"created": "2024-09-23T06:52:14.730Z",
"currency": "USD",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Default value",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": null,
"card_type": null,
"card_network": "Visa",
"card_issuer": "",
"card_issuing_country": null,
"card_isin": null,
"card_extended_bin": null,
"card_exp_month": null,
"card_exp_year": null,
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "billing_email@gmail.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "pay_2dJSM6oUYFoKtxtD45jm",
"frm_message": null,
"metadata": {
"order_details": {
"amount": 10000,
"quantity": 1,
"product_name": "Apple iphone 15"
}
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ClRdOxbia1VPXGEvFHe3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_fBms1u3jKBroyqKUax5S",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
},
{
"payment_id": "pay_8rF6jCw4J0W4e2eV7WqC",
"merchant_id": "merchant_1726749985",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 10000,
"amount_received": null,
"connector": null,
"client_secret": "pay_8rF6jCw4J0W4e2eV7WqC_secret_LuwsymB20YhQ1MaujKgK",
"created": "2024-09-23T06:50:09.337Z",
"currency": "USD",
"customer_id": "hyperswitch_sdk_demo_id",
"customer": {
"id": "hyperswitch_sdk_demo_id",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Default value",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": {
"card": {
"last4": null,
"card_type": null,
"card_network": "Visa",
"card_issuer": "",
"card_issuing_country": null,
"card_isin": null,
"card_extended_bin": null,
"card_exp_month": null,
"card_exp_year": null,
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "billing_email@gmail.com"
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"order_details": {
"amount": 10000,
"quantity": 1,
"product_name": "Apple iphone 15"
}
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ClRdOxbia1VPXGEvFHe3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
]
}
```
| [
"crates/api_models/src/payments.rs",
"crates/hyperswitch_domain_models/src/payments/payment_intent.rs",
"crates/router/src/core/payments.rs",
"crates/storage_impl/src/payments/payment_intent.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-6002 | Bug: [FEATURE] [CRYPTOPAY] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `cryptopay` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `cryptopay` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 48c50936d60..f057b7d4a33 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,5 +1,8 @@
pub mod bambora;
pub mod bitpay;
+pub mod cashtocode;
+pub mod coinbase;
+pub mod cryptopay;
pub mod deutschebank;
pub mod fiserv;
pub mod fiservemea;
@@ -18,8 +21,9 @@ pub mod volt;
pub mod worldline;
pub use self::{
- bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv,
- fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie,
- nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar,
- thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
+ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
+ cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea,
+ fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay,
+ novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
+ tsys::Tsys, volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
similarity index 67%
rename from crates/router/src/connector/cashtocode.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs
index 2155b80dd81..c72b63aebc0 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
@@ -1,33 +1,41 @@
pub mod transformers;
-
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as cashtocode;
-
-use super::utils as connector_utils;
-use crate::{
- configs::settings::{self},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ api::ApplicationResponse,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- storage, ErrorResponse, Response,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
- utils::{ByteSliceExt, BytesExt},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers as cashtocode;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
@@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
- payment_method_type: &Option<storage::enums::PaymentMethodType>,
+ payment_method_type: &Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
-) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
- ) -> Result<request::Maskable<String>, errors::ConnectorError> {
+ ) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
@@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode(
}
let auth_header = match payment_method_type {
- Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
+ Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
- Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth(
+ Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
@@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode(
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cashtocode
{
// Not Implemented (R)
}
@@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
@@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cashtocode
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cashtocode
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
@@ -193,17 +184,15 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_owned()
.into(),
)];
@@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/merchant/paytokens",
@@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode PaymentsAuthorizeResponse")
@@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
@@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
@@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cashtocode {
+impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let base64_signature =
- connector_utils::get_header_key_value("authorization", request.headers)?;
+ let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
@@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
@@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_api_response(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode {
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
- Ok(services::api::ApplicationResponse::Json(response))
+ Ok(ApplicationResponse::Json(response))
}
}
-impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::refunds::Execute,
- types::RefundsData,
- types::RefundsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Execute, RefundsData, RefundsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
@@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu
}
}
-impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
similarity index 81%
rename from crates/router/src/connector/cashtocode/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index e6f4b9e57cf..49493127621 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -1,18 +1,24 @@
use std::collections::HashMap;
+use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types::PaymentsAuthorizeRouterData,
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, storage::enums},
+ types::ResponseRouterData,
+ utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
@@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest {
}
fn get_mid(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
@@ -50,10 +56,10 @@ fn get_mid(
}
}
-impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
+impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit),
+ (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
@@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco
item.request.currency,
)?;
match item.payment_method {
- diesel_models::enums::PaymentMethod::Reward => Ok(Self {
+ enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
@@ -96,12 +102,12 @@ pub struct CashtocodeAuth {
pub merchant_id_evoucher: Option<Secret<String>>,
}
-impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
+impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
+ ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
@@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
}
}
-impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
+impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
+ fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
- if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
+ if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
@@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse {
fn get_redirect_form_data(
payment_method_type: &enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
-) -> CustomResult<services::RedirectForm, errors::ConnectorError> {
+) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
- enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form {
+ enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
- enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from((
+ enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
@@ -220,27 +226,27 @@ fn get_redirect_form_data(
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description,
@@ -259,8 +265,8 @@ impl<F>
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Some(redirection_data),
@@ -283,29 +289,17 @@ impl<F>
}
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: None,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
similarity index 64%
rename from crates/router/src/connector/coinbase.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs
index 0c3c0be41db..7b149952ca8 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
@@ -2,31 +2,45 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as coinbase;
-
-use self::coinbase::CoinbaseWebhookDetails;
-use super::utils;
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::Mask;
+use transformers as coinbase;
+
+use self::coinbase::CoinbaseWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Coinbase;
@@ -50,9 +64,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Coinbase
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Coinbase
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Coinbase
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
@@ -178,14 +175,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
@@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
@@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Coinbase
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
@@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Coinbase {
+impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
@@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
similarity index 87%
rename from crates/router/src/connector/coinbase/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index 82a6add72ee..3633c366c4c 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -1,15 +1,24 @@
use std::collections::HashMap;
-use common_utils::pii;
+use common_enums::enums;
+use common_utils::{pii, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- pii::Secret,
- services,
- types::{self, api, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
+ },
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
@@ -46,10 +55,10 @@ pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType {
+impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type {
+ fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
@@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse {
data: CoinbasePaymentResponseData,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CoinbasePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm::Form {
+ let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
- method: services::Method::Get,
+ method: Method::Get,
form_fields,
};
let timeline = item
@@ -138,10 +141,10 @@ impl<F, T>
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
- Ok(types::PaymentsResponseData::TransactionResponse {
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Some(redirection_data),
mandate_reference: None,
@@ -152,9 +155,9 @@ impl<F, T>
charge_id: None,
}),
|context| {
- Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
+ Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
- reason: Some(api::enums::UnresolvedResponseReason {
+ reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
@@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ _item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
@@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ _item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
similarity index 69%
rename from crates/router/src/connector/cryptopay.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs
index 765a07646c6..dcd629f4336 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
@@ -4,35 +4,44 @@ use base64::Engine;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
-use masking::PeekInterface;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
use transformers as cryptopay;
use self::cryptopay::CryptopayWebhookDetails;
-use super::utils;
use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, ForeignTryFrom},
};
#[derive(Clone)]
@@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {}
impl api::RefundSync for Cryptopay {}
impl api::PaymentToken for Cryptopay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cryptopay
{
// Not Implemented (R)
}
@@ -77,16 +82,13 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let method = self.get_http_method();
let payload = match method {
- common_utils::request::Method::Get => String::default(),
- common_utils::request::Method::Post
- | common_utils::request::Method::Put
- | common_utils::request::Method::Delete
- | common_utils::request::Method::Patch => {
+ Method::Get => String::default(),
+ Method::Post | Method::Put | Method::Delete | Method::Patch => {
let body = self
.get_request_body(req, connectors)?
.get_inner_value()
@@ -121,7 +123,7 @@ where
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
- let authz = consts::BASE64_ENGINE.encode(authz);
+ let authz = common_utils::consts::BASE64_ENGINE.encode(authz);
let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz);
let headers = vec![
@@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cryptopay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = cryptopay::CryptopayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cryptopay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string())
.into(),
@@ -225,14 +213,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
@@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay PaymentsAuthorizeResponse")
@@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
impl ConnectorValidation for Cryptopay {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay {
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
self.common_get_content_type()
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let custom_id = req.connector_request_reference_id.clone();
Ok(format!(
@@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay PaymentsSyncResponse")
@@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cryptopay {
+impl webhooks::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
@@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
@@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay {
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.data.status {
cryptopay::CryptopayPaymentStatus::Completed => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
cryptopay::CryptopayPaymentStatus::Unresolved => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
cryptopay::CryptopayPaymentStatus::Cancelled => {
- Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
- _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
similarity index 76%
rename from crates/router/src/connector/cryptopay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index cd22890ca52..03a585f76bd 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -1,17 +1,23 @@
+use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
- consts,
- core::errors,
- services,
- types::{self, domain, storage::enums, transformers::ForeignTryFrom},
+ types::ResponseRouterData,
+ utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
@@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Crypto(ref cryptodata) => {
+ PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
@@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("CryptoPay"),
- ))
- }
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("CryptoPay"),
+ )),
}?;
Ok(cryptopay_request)
}
@@ -96,10 +100,10 @@ pub struct CryptopayAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType {
+impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
@@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse {
impl<F, T>
ForeignTryFrom<(
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ )> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: payment_response
.name
.clone()
@@ -173,11 +177,9 @@ impl<F, T>
.response
.data
.hosted_page_url
- .map(|x| services::RedirectForm::from((x, services::Method::Get)));
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.data.id.clone(),
- ),
+ .map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 1093ef4e6f0..953b6316ff8 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
- utils::{self, AddressDetailsData, RouterData as _},
+ utils::{self, is_payment_failure, AddressDetailsData, RouterData as _},
};
const PASSWORD: &str = "password";
@@ -605,32 +605,3 @@ pub struct VoltErrorList {
pub property: String,
pub message: String,
}
-
-fn is_payment_failure(status: enums::AttemptStatus) -> bool {
- match status {
- common_enums::AttemptStatus::AuthenticationFailed
- | common_enums::AttemptStatus::AuthorizationFailed
- | common_enums::AttemptStatus::CaptureFailed
- | common_enums::AttemptStatus::VoidFailed
- | common_enums::AttemptStatus::Failure => true,
- common_enums::AttemptStatus::Started
- | common_enums::AttemptStatus::RouterDeclined
- | common_enums::AttemptStatus::AuthenticationPending
- | common_enums::AttemptStatus::AuthenticationSuccessful
- | common_enums::AttemptStatus::Authorized
- | common_enums::AttemptStatus::Charged
- | common_enums::AttemptStatus::Authorizing
- | common_enums::AttemptStatus::CodInitiated
- | common_enums::AttemptStatus::Voided
- | common_enums::AttemptStatus::VoidInitiated
- | common_enums::AttemptStatus::CaptureInitiated
- | common_enums::AttemptStatus::AutoRefunded
- | common_enums::AttemptStatus::PartialCharged
- | common_enums::AttemptStatus::PartialChargedAndChargeable
- | common_enums::AttemptStatus::Unresolved
- | common_enums::AttemptStatus::Pending
- | common_enums::AttemptStatus::PaymentMethodAwaited
- | common_enums::AttemptStatus::ConfirmationAwaited
- | common_enums::AttemptStatus::DeviceDataCollectionPending => false,
- }
-}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index c5ca6512a34..4c27e11fc45 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -10,6 +10,8 @@ pub(crate) mod headers {
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
+ pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
+ pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index a667c5ddc3c..31052ab0df2 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token {
default_imp_for_authorize_session_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax {
default_imp_for_calculate_tax!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update {
default_imp_for_session_update!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization {
default_imp_for_incremental_authorization!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer {
default_imp_for_create_customer!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response {
default_imp_for_connector_redirect_response!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{
default_imp_for_post_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve {
default_imp_for_approve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject {
default_imp_for_reject!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification {
default_imp_for_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute {
default_imp_for_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence {
default_imp_for_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute {
default_imp_for_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload {
default_imp_for_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create {
default_imp_for_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve {
default_imp_for_payouts_retrieve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility {
default_imp_for_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill {
default_imp_for_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel {
default_imp_for_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote {
default_imp_for_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient {
default_imp_for_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account {
default_imp_for_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale {
default_imp_for_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout {
default_imp_for_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction {
default_imp_for_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment {
default_imp_for_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return {
default_imp_for_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates {
default_imp_for_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 3bb1abfef21..16e592688ac 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index b2979975e55..f96d715f5be 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount
use base64::Engine;
use common_enums::{
enums,
- enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
+ enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
};
use common_utils::{
consts::BASE64_ENGINE,
@@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>(
.change_context(errors::ConnectorError::AmountConversionFailed)
}
+pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
+ match status {
+ AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::Failure => true,
+ AttemptStatus::Started
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::Authorized
+ | AttemptStatus::Charged
+ | AttemptStatus::Authorizing
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::Voided
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::AutoRefunded
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::Unresolved
+ | AttemptStatus::Pending
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::DeviceDataCollectionPending => false,
+ }
+}
+
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -1460,6 +1489,18 @@ fn get_header_field(
))?
}
+pub trait CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error>;
+}
+
+impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error> {
+ self.pay_currency
+ .clone()
+ .ok_or_else(missing_field_err("crypto_data.pay_currency"))
+ }
+}
+
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index b505f8c8c52..116fc67320f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -9,10 +9,7 @@ pub mod billwerk;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
-pub mod cashtocode;
pub mod checkout;
-pub mod coinbase;
-pub mod cryptopay;
pub mod cybersource;
pub mod datatrans;
pub mod dlocal;
@@ -62,12 +59,13 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank,
- fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
- globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
- nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax,
- stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt,
- worldline, worldline::Worldline,
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
+ coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
+ deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
+ fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie,
+ nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
+ stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt,
+ volt::Volt, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
- billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
- cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
+ billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 041b5bb7359..3ff93cf9bf0 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e364d662e24..f9a6b461a13 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -209,10 +209,7 @@ default_imp_for_complete_authorize!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!(
connector::Bluesnap,
connector::Braintree,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -376,10 +370,7 @@ default_imp_for_create_customer!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -630,9 +618,6 @@ default_imp_for_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -739,9 +724,6 @@ default_imp_for_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -825,10 +807,7 @@ default_imp_for_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -911,10 +890,7 @@ default_imp_for_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1946,11 +1892,8 @@ default_imp_for_approve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2035,11 +1978,8 @@ default_imp_for_reject!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3158,10 +3071,7 @@ default_imp_for_session_update!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
| 2024-09-20T18:00:15Z |
## 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/5629
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials. | d9270ace8ddde16eca8c45ceb79af3e4d815d7cd |
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials.
| [
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/cashtocode.rs",
"crates/router/src/connector/cashtocode/transformers.rs",
"crates/router/src/connector/coinbase.rs",
"crates/router/src/connector/coinbase/transformers.rs",
"crates/router/src/connector/cryptopay.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-6001 | Bug: [FEATURE] [CASHTOCODE] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `cashtocode` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `cashtocode` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 48c50936d60..f057b7d4a33 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,5 +1,8 @@
pub mod bambora;
pub mod bitpay;
+pub mod cashtocode;
+pub mod coinbase;
+pub mod cryptopay;
pub mod deutschebank;
pub mod fiserv;
pub mod fiservemea;
@@ -18,8 +21,9 @@ pub mod volt;
pub mod worldline;
pub use self::{
- bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv,
- fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie,
- nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar,
- thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
+ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
+ cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea,
+ fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay,
+ novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
+ tsys::Tsys, volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
similarity index 67%
rename from crates/router/src/connector/cashtocode.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs
index 2155b80dd81..c72b63aebc0 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
@@ -1,33 +1,41 @@
pub mod transformers;
-
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as cashtocode;
-
-use super::utils as connector_utils;
-use crate::{
- configs::settings::{self},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ api::ApplicationResponse,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- storage, ErrorResponse, Response,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
- utils::{ByteSliceExt, BytesExt},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers as cashtocode;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
@@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
- payment_method_type: &Option<storage::enums::PaymentMethodType>,
+ payment_method_type: &Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
-) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
- ) -> Result<request::Maskable<String>, errors::ConnectorError> {
+ ) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
@@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode(
}
let auth_header = match payment_method_type {
- Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
+ Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
- Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth(
+ Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
@@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode(
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cashtocode
{
// Not Implemented (R)
}
@@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
@@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cashtocode
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cashtocode
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
@@ -193,17 +184,15 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_owned()
.into(),
)];
@@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/merchant/paytokens",
@@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode PaymentsAuthorizeResponse")
@@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
@@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
@@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cashtocode {
+impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let base64_signature =
- connector_utils::get_header_key_value("authorization", request.headers)?;
+ let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
@@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
@@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_api_response(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode {
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
- Ok(services::api::ApplicationResponse::Json(response))
+ Ok(ApplicationResponse::Json(response))
}
}
-impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::refunds::Execute,
- types::RefundsData,
- types::RefundsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Execute, RefundsData, RefundsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
@@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu
}
}
-impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
similarity index 81%
rename from crates/router/src/connector/cashtocode/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index e6f4b9e57cf..49493127621 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -1,18 +1,24 @@
use std::collections::HashMap;
+use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types::PaymentsAuthorizeRouterData,
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, storage::enums},
+ types::ResponseRouterData,
+ utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
@@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest {
}
fn get_mid(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
@@ -50,10 +56,10 @@ fn get_mid(
}
}
-impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
+impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit),
+ (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
@@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco
item.request.currency,
)?;
match item.payment_method {
- diesel_models::enums::PaymentMethod::Reward => Ok(Self {
+ enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
@@ -96,12 +102,12 @@ pub struct CashtocodeAuth {
pub merchant_id_evoucher: Option<Secret<String>>,
}
-impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
+impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
+ ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
@@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
}
}
-impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
+impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
+ fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
- if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
+ if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
@@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse {
fn get_redirect_form_data(
payment_method_type: &enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
-) -> CustomResult<services::RedirectForm, errors::ConnectorError> {
+) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
- enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form {
+ enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
- enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from((
+ enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
@@ -220,27 +226,27 @@ fn get_redirect_form_data(
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description,
@@ -259,8 +265,8 @@ impl<F>
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Some(redirection_data),
@@ -283,29 +289,17 @@ impl<F>
}
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: None,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
similarity index 64%
rename from crates/router/src/connector/coinbase.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs
index 0c3c0be41db..7b149952ca8 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
@@ -2,31 +2,45 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as coinbase;
-
-use self::coinbase::CoinbaseWebhookDetails;
-use super::utils;
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::Mask;
+use transformers as coinbase;
+
+use self::coinbase::CoinbaseWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Coinbase;
@@ -50,9 +64,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Coinbase
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Coinbase
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Coinbase
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
@@ -178,14 +175,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
@@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
@@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Coinbase
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
@@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Coinbase {
+impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
@@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
similarity index 87%
rename from crates/router/src/connector/coinbase/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index 82a6add72ee..3633c366c4c 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -1,15 +1,24 @@
use std::collections::HashMap;
-use common_utils::pii;
+use common_enums::enums;
+use common_utils::{pii, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- pii::Secret,
- services,
- types::{self, api, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
+ },
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
@@ -46,10 +55,10 @@ pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType {
+impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type {
+ fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
@@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse {
data: CoinbasePaymentResponseData,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CoinbasePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm::Form {
+ let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
- method: services::Method::Get,
+ method: Method::Get,
form_fields,
};
let timeline = item
@@ -138,10 +141,10 @@ impl<F, T>
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
- Ok(types::PaymentsResponseData::TransactionResponse {
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Some(redirection_data),
mandate_reference: None,
@@ -152,9 +155,9 @@ impl<F, T>
charge_id: None,
}),
|context| {
- Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
+ Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
- reason: Some(api::enums::UnresolvedResponseReason {
+ reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
@@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ _item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
@@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ _item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
similarity index 69%
rename from crates/router/src/connector/cryptopay.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs
index 765a07646c6..dcd629f4336 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
@@ -4,35 +4,44 @@ use base64::Engine;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
-use masking::PeekInterface;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
use transformers as cryptopay;
use self::cryptopay::CryptopayWebhookDetails;
-use super::utils;
use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, ForeignTryFrom},
};
#[derive(Clone)]
@@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {}
impl api::RefundSync for Cryptopay {}
impl api::PaymentToken for Cryptopay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cryptopay
{
// Not Implemented (R)
}
@@ -77,16 +82,13 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let method = self.get_http_method();
let payload = match method {
- common_utils::request::Method::Get => String::default(),
- common_utils::request::Method::Post
- | common_utils::request::Method::Put
- | common_utils::request::Method::Delete
- | common_utils::request::Method::Patch => {
+ Method::Get => String::default(),
+ Method::Post | Method::Put | Method::Delete | Method::Patch => {
let body = self
.get_request_body(req, connectors)?
.get_inner_value()
@@ -121,7 +123,7 @@ where
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
- let authz = consts::BASE64_ENGINE.encode(authz);
+ let authz = common_utils::consts::BASE64_ENGINE.encode(authz);
let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz);
let headers = vec![
@@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cryptopay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = cryptopay::CryptopayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cryptopay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string())
.into(),
@@ -225,14 +213,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
@@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay PaymentsAuthorizeResponse")
@@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
impl ConnectorValidation for Cryptopay {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay {
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
self.common_get_content_type()
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let custom_id = req.connector_request_reference_id.clone();
Ok(format!(
@@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay PaymentsSyncResponse")
@@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cryptopay {
+impl webhooks::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
@@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
@@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay {
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.data.status {
cryptopay::CryptopayPaymentStatus::Completed => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
cryptopay::CryptopayPaymentStatus::Unresolved => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
cryptopay::CryptopayPaymentStatus::Cancelled => {
- Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
- _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
similarity index 76%
rename from crates/router/src/connector/cryptopay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index cd22890ca52..03a585f76bd 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -1,17 +1,23 @@
+use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
- consts,
- core::errors,
- services,
- types::{self, domain, storage::enums, transformers::ForeignTryFrom},
+ types::ResponseRouterData,
+ utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
@@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Crypto(ref cryptodata) => {
+ PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
@@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("CryptoPay"),
- ))
- }
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("CryptoPay"),
+ )),
}?;
Ok(cryptopay_request)
}
@@ -96,10 +100,10 @@ pub struct CryptopayAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType {
+impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
@@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse {
impl<F, T>
ForeignTryFrom<(
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ )> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: payment_response
.name
.clone()
@@ -173,11 +177,9 @@ impl<F, T>
.response
.data
.hosted_page_url
- .map(|x| services::RedirectForm::from((x, services::Method::Get)));
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.data.id.clone(),
- ),
+ .map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 1093ef4e6f0..953b6316ff8 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
- utils::{self, AddressDetailsData, RouterData as _},
+ utils::{self, is_payment_failure, AddressDetailsData, RouterData as _},
};
const PASSWORD: &str = "password";
@@ -605,32 +605,3 @@ pub struct VoltErrorList {
pub property: String,
pub message: String,
}
-
-fn is_payment_failure(status: enums::AttemptStatus) -> bool {
- match status {
- common_enums::AttemptStatus::AuthenticationFailed
- | common_enums::AttemptStatus::AuthorizationFailed
- | common_enums::AttemptStatus::CaptureFailed
- | common_enums::AttemptStatus::VoidFailed
- | common_enums::AttemptStatus::Failure => true,
- common_enums::AttemptStatus::Started
- | common_enums::AttemptStatus::RouterDeclined
- | common_enums::AttemptStatus::AuthenticationPending
- | common_enums::AttemptStatus::AuthenticationSuccessful
- | common_enums::AttemptStatus::Authorized
- | common_enums::AttemptStatus::Charged
- | common_enums::AttemptStatus::Authorizing
- | common_enums::AttemptStatus::CodInitiated
- | common_enums::AttemptStatus::Voided
- | common_enums::AttemptStatus::VoidInitiated
- | common_enums::AttemptStatus::CaptureInitiated
- | common_enums::AttemptStatus::AutoRefunded
- | common_enums::AttemptStatus::PartialCharged
- | common_enums::AttemptStatus::PartialChargedAndChargeable
- | common_enums::AttemptStatus::Unresolved
- | common_enums::AttemptStatus::Pending
- | common_enums::AttemptStatus::PaymentMethodAwaited
- | common_enums::AttemptStatus::ConfirmationAwaited
- | common_enums::AttemptStatus::DeviceDataCollectionPending => false,
- }
-}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index c5ca6512a34..4c27e11fc45 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -10,6 +10,8 @@ pub(crate) mod headers {
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
+ pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
+ pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index a667c5ddc3c..31052ab0df2 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token {
default_imp_for_authorize_session_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax {
default_imp_for_calculate_tax!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update {
default_imp_for_session_update!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization {
default_imp_for_incremental_authorization!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer {
default_imp_for_create_customer!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response {
default_imp_for_connector_redirect_response!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{
default_imp_for_post_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve {
default_imp_for_approve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject {
default_imp_for_reject!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification {
default_imp_for_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute {
default_imp_for_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence {
default_imp_for_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute {
default_imp_for_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload {
default_imp_for_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create {
default_imp_for_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve {
default_imp_for_payouts_retrieve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility {
default_imp_for_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill {
default_imp_for_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel {
default_imp_for_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote {
default_imp_for_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient {
default_imp_for_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account {
default_imp_for_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale {
default_imp_for_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout {
default_imp_for_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction {
default_imp_for_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment {
default_imp_for_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return {
default_imp_for_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates {
default_imp_for_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 3bb1abfef21..16e592688ac 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index b2979975e55..f96d715f5be 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount
use base64::Engine;
use common_enums::{
enums,
- enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
+ enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
};
use common_utils::{
consts::BASE64_ENGINE,
@@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>(
.change_context(errors::ConnectorError::AmountConversionFailed)
}
+pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
+ match status {
+ AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::Failure => true,
+ AttemptStatus::Started
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::Authorized
+ | AttemptStatus::Charged
+ | AttemptStatus::Authorizing
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::Voided
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::AutoRefunded
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::Unresolved
+ | AttemptStatus::Pending
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::DeviceDataCollectionPending => false,
+ }
+}
+
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -1460,6 +1489,18 @@ fn get_header_field(
))?
}
+pub trait CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error>;
+}
+
+impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error> {
+ self.pay_currency
+ .clone()
+ .ok_or_else(missing_field_err("crypto_data.pay_currency"))
+ }
+}
+
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index b505f8c8c52..116fc67320f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -9,10 +9,7 @@ pub mod billwerk;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
-pub mod cashtocode;
pub mod checkout;
-pub mod coinbase;
-pub mod cryptopay;
pub mod cybersource;
pub mod datatrans;
pub mod dlocal;
@@ -62,12 +59,13 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank,
- fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
- globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
- nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax,
- stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt,
- worldline, worldline::Worldline,
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
+ coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
+ deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
+ fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie,
+ nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
+ stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt,
+ volt::Volt, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
- billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
- cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
+ billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 041b5bb7359..3ff93cf9bf0 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e364d662e24..f9a6b461a13 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -209,10 +209,7 @@ default_imp_for_complete_authorize!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!(
connector::Bluesnap,
connector::Braintree,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -376,10 +370,7 @@ default_imp_for_create_customer!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -630,9 +618,6 @@ default_imp_for_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -739,9 +724,6 @@ default_imp_for_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -825,10 +807,7 @@ default_imp_for_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -911,10 +890,7 @@ default_imp_for_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1946,11 +1892,8 @@ default_imp_for_approve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2035,11 +1978,8 @@ default_imp_for_reject!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3158,10 +3071,7 @@ default_imp_for_session_update!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
| 2024-09-20T18:00:15Z |
## 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/5629
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials. | d9270ace8ddde16eca8c45ceb79af3e4d815d7cd |
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials.
| [
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/cashtocode.rs",
"crates/router/src/connector/cashtocode/transformers.rs",
"crates/router/src/connector/coinbase.rs",
"crates/router/src/connector/coinbase/transformers.rs",
"crates/router/src/connector/cryptopay.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-5629 | Bug: [FEATURE] [COINBASE] Move connector code to crate hyperswitch_connectors
### Feature Description
Connector code for `coinbase` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Possible Implementation
Connector code for `coinbase` needs to be moved from crate `router` to new crate `hyperswitch_connectors`
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 48c50936d60..f057b7d4a33 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,5 +1,8 @@
pub mod bambora;
pub mod bitpay;
+pub mod cashtocode;
+pub mod coinbase;
+pub mod cryptopay;
pub mod deutschebank;
pub mod fiserv;
pub mod fiservemea;
@@ -18,8 +21,9 @@ pub mod volt;
pub mod worldline;
pub use self::{
- bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv,
- fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie,
- nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar,
- thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
+ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase,
+ cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea,
+ fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay,
+ novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes,
+ tsys::Tsys, volt::Volt, worldline::Worldline,
};
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
similarity index 67%
rename from crates/router/src/connector/cashtocode.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs
index 2155b80dd81..c72b63aebc0 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs
@@ -1,33 +1,41 @@
pub mod transformers;
-
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
-use transformers as cashtocode;
-
-use super::utils as connector_utils;
-use crate::{
- configs::settings::{self},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ api::ApplicationResponse,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- storage, ErrorResponse, Response,
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
},
- utils::{ByteSliceExt, BytesExt},
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface, Secret};
+use transformers as cashtocode;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
@@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
- payment_method_type: &Option<storage::enums::PaymentMethodType>,
+ payment_method_type: &Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
-) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
- ) -> Result<request::Maskable<String>, errors::ConnectorError> {
+ ) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
@@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode(
}
let auth_header = match payment_method_type {
- Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
+ Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
- Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth(
+ Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
@@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode(
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cashtocode
{
// Not Implemented (R)
}
@@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
@@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cashtocode
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cashtocode
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cashtocode
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
@@ -193,17 +184,15 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_owned()
.into(),
)];
@@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/merchant/paytokens",
@@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode PaymentsAuthorizeResponse")
@@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::Capture,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
@@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
@@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cashtocode {
+impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let base64_signature =
- connector_utils::get_header_key_value("authorization", request.headers)?;
+ let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
@@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
@@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode {
fn get_webhook_api_response(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError>
- {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
@@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode {
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
- Ok(services::api::ApplicationResponse::Json(response))
+ Ok(ApplicationResponse::Json(response))
}
}
-impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
- _req: &types::RouterData<
- api::refunds::Execute,
- types::RefundsData,
- types::RefundsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<Execute, RefundsData, RefundsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
@@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu
}
}
-impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData>
- for Cashtocode
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
similarity index 81%
rename from crates/router/src/connector/cashtocode/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index e6f4b9e57cf..49493127621 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -1,18 +1,24 @@
use std::collections::HashMap;
+use common_enums::enums;
pub use common_utils::request::Method;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types::PaymentsAuthorizeRouterData,
+};
+use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, storage::enums},
+ types::ResponseRouterData,
+ utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Default, Debug, Serialize)]
@@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest {
}
fn get_mid(
- connector_auth_type: &types::ConnectorAuthType,
+ connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<enums::PaymentMethodType>,
currency: enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
@@ -50,10 +56,10 @@ fn get_mid(
}
}
-impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
+impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit),
+ (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let customer_id = item.get_customer_id()?;
let url = item.request.get_router_return_url()?;
@@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco
item.request.currency,
)?;
match item.payment_method {
- diesel_models::enums::PaymentMethod::Reward => Ok(Self {
+ enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item.attempt_id.clone(),
currency: item.request.currency,
@@ -96,12 +102,12 @@ pub struct CashtocodeAuth {
pub merchant_id_evoucher: Option<Secret<String>>,
}
-impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
+impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
+ ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
@@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType {
}
}
-impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
+impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
+ fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
- if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
+ if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
@@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse {
fn get_redirect_form_data(
payment_method_type: &enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
-) -> CustomResult<services::RedirectForm, errors::ConnectorError> {
+) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
- enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form {
+ enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
- enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from((
+ enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from((
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
response_data.pay_url,
Method::Get,
@@ -220,27 +226,27 @@ fn get_redirect_form_data(
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CashtocodePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match item.response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
enums::AttemptStatus::Failure,
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description,
@@ -259,8 +265,8 @@ impl<F>
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
enums::AttemptStatus::AuthenticationPending,
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
redirection_data: Some(redirection_data),
@@ -283,29 +289,17 @@ impl<F>
}
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CashtocodePaymentsSyncResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction.
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id
),
redirection_data: None,
diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
similarity index 64%
rename from crates/router/src/connector/coinbase.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs
index 0c3c0be41db..7b149952ca8 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs
@@ -2,31 +2,45 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as coinbase;
-
-use self::coinbase::CoinbaseWebhookDetails;
-use super::utils;
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
},
- utils::BytesExt,
};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::Mask;
+use transformers as coinbase;
+
+use self::coinbase::CoinbaseWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Debug, Clone)]
pub struct Coinbase;
@@ -50,9 +64,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase {
match capture_method {
enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Coinbase
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Coinbase
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Coinbase
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Coinbase
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
@@ -178,14 +175,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
@@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
@@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Coinbase
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Coinbase
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
@@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Coinbase {
+impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
@@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
similarity index 87%
rename from crates/router/src/connector/coinbase/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index 82a6add72ee..3633c366c4c 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -1,15 +1,24 @@
use std::collections::HashMap;
-use common_utils::pii;
+use common_enums::enums;
+use common_utils::{pii, request::Method};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- pii::Secret,
- services,
- types::{self, api, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData,
+ },
};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
@@ -46,10 +55,10 @@ pub struct CoinbaseAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType {
+impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type {
+ fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::HeaderKey { api_key } = _auth_type {
Ok(Self {
api_key: api_key.to_owned(),
})
@@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse {
data: CoinbasePaymentResponseData,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- CoinbasePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm::Form {
+ let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_url.to_string(),
- method: services::Method::Get,
+ method: Method::Get,
form_fields,
};
let timeline = item
@@ -138,10 +141,10 @@ impl<F, T>
.last()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.clone();
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone());
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone());
let attempt_status = timeline.status.clone();
let response_data = timeline.context.map_or(
- Ok(types::PaymentsResponseData::TransactionResponse {
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
redirection_data: Some(redirection_data),
mandate_reference: None,
@@ -152,9 +155,9 @@ impl<F, T>
charge_id: None,
}),
|context| {
- Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
+ Ok(PaymentsResponseData::TransactionUnresolvedResponse{
resource_id: connector_id,
- reason: Some(api::enums::UnresolvedResponseReason {
+ reason: Some(api_models::enums::UnresolvedResponseReason {
code: context.to_string(),
message: "Please check the transaction in coinbase dashboard and resolve manually"
.to_string(),
@@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus {
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
+ for types::RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ _item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
@@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ _item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Err(errors::ConnectorError::NotImplemented(
"try_from RefundsResponseRouterData".to_string(),
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
similarity index 69%
rename from crates/router/src/connector/cryptopay.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs
index 765a07646c6..dcd629f4336 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs
@@ -4,35 +4,44 @@ use base64::Engine;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
-use masking::PeekInterface;
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData},
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
use transformers as cryptopay;
use self::cryptopay::CryptopayWebhookDetails;
-use super::utils;
use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, ForeignTryFrom},
};
#[derive(Clone)]
@@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {}
impl api::RefundSync for Cryptopay {}
impl api::PaymentToken for Cryptopay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cryptopay
{
// Not Implemented (R)
}
@@ -77,16 +82,13 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let method = self.get_http_method();
let payload = match method {
- common_utils::request::Method::Get => String::default(),
- common_utils::request::Method::Post
- | common_utils::request::Method::Put
- | common_utils::request::Method::Delete
- | common_utils::request::Method::Patch => {
+ Method::Get => String::default(),
+ Method::Post | Method::Put | Method::Delete | Method::Patch => {
let body = self
.get_request_body(req, connectors)?
.get_inner_value()
@@ -121,7 +123,7 @@ where
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
- let authz = consts::BASE64_ENGINE.encode(authz);
+ let authz = common_utils::consts::BASE64_ENGINE.encode(authz);
let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz);
let headers = vec![
@@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cryptopay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = cryptopay::CryptopayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cryptopay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cryptopay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string())
.into(),
@@ -225,14 +213,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/api/invoices", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
@@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("Cryptopay PaymentsAuthorizeResponse")
@@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
impl ConnectorValidation for Cryptopay {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay {
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cryptopay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
self.common_get_content_type()
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Get
+ fn get_http_method(&self) -> Method {
+ Method::Get
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let custom_id = req.connector_request_reference_id.clone();
Ok(format!(
@@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: cryptopay::CryptopayPaymentsResponse = res
.response
.parse_struct("cryptopay PaymentsSyncResponse")
@@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
)?),
None => None,
};
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Cryptopay
-{
-}
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cryptopay {
+impl webhooks::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
@@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
@@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
.body
@@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay {
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.data.status {
cryptopay::CryptopayPaymentStatus::Completed => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
cryptopay::CryptopayPaymentStatus::Unresolved => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
cryptopay::CryptopayPaymentStatus::Cancelled => {
- Ok(api::IncomingWebhookEvent::PaymentIntentFailure)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
- _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CryptopayWebhookDetails =
request
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
similarity index 76%
rename from crates/router/src/connector/cryptopay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index cd22890ca52..03a585f76bd 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -1,17 +1,23 @@
+use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm},
+ types,
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
- consts,
- core::errors,
- services,
- types::{self, domain, storage::enums, transformers::ForeignTryFrom},
+ types::ResponseRouterData,
+ utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData},
};
#[derive(Debug, Serialize)]
@@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let cryptopay_request = match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Crypto(ref cryptodata) => {
+ PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
price_amount: item.amount.clone(),
@@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
custom_id: item.router_data.connector_request_reference_id.clone(),
})
}
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("CryptoPay"),
- ))
- }
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("CryptoPay"),
+ )),
}?;
Ok(cryptopay_request)
}
@@ -96,10 +100,10 @@ pub struct CryptopayAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType {
+impl TryFrom<&ConnectorAuthType> for CryptopayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
@@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse {
impl<F, T>
ForeignTryFrom<(
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ )> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, amount_captured_in_minor_units): (
- types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
+ ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>,
Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
let payment_response = &item.response.data;
- Err(types::ErrorResponse {
+ Err(ErrorResponse {
code: payment_response
.name
.clone()
@@ -173,11 +177,9 @@ impl<F, T>
.response
.data
.hosted_page_url
- .map(|x| services::RedirectForm::from((x, services::Method::Get)));
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.data.id.clone(),
- ),
+ .map(|x| RedirectForm::from((x, common_utils::request::Method::Get)));
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()),
redirection_data,
mandate_reference: None,
connector_metadata: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index 1093ef4e6f0..953b6316ff8 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData},
- utils::{self, AddressDetailsData, RouterData as _},
+ utils::{self, is_payment_failure, AddressDetailsData, RouterData as _},
};
const PASSWORD: &str = "password";
@@ -605,32 +605,3 @@ pub struct VoltErrorList {
pub property: String,
pub message: String,
}
-
-fn is_payment_failure(status: enums::AttemptStatus) -> bool {
- match status {
- common_enums::AttemptStatus::AuthenticationFailed
- | common_enums::AttemptStatus::AuthorizationFailed
- | common_enums::AttemptStatus::CaptureFailed
- | common_enums::AttemptStatus::VoidFailed
- | common_enums::AttemptStatus::Failure => true,
- common_enums::AttemptStatus::Started
- | common_enums::AttemptStatus::RouterDeclined
- | common_enums::AttemptStatus::AuthenticationPending
- | common_enums::AttemptStatus::AuthenticationSuccessful
- | common_enums::AttemptStatus::Authorized
- | common_enums::AttemptStatus::Charged
- | common_enums::AttemptStatus::Authorizing
- | common_enums::AttemptStatus::CodInitiated
- | common_enums::AttemptStatus::Voided
- | common_enums::AttemptStatus::VoidInitiated
- | common_enums::AttemptStatus::CaptureInitiated
- | common_enums::AttemptStatus::AutoRefunded
- | common_enums::AttemptStatus::PartialCharged
- | common_enums::AttemptStatus::PartialChargedAndChargeable
- | common_enums::AttemptStatus::Unresolved
- | common_enums::AttemptStatus::Pending
- | common_enums::AttemptStatus::PaymentMethodAwaited
- | common_enums::AttemptStatus::ConfirmationAwaited
- | common_enums::AttemptStatus::DeviceDataCollectionPending => false,
- }
-}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index c5ca6512a34..4c27e11fc45 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -10,6 +10,8 @@ pub(crate) mod headers {
pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
+ pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key";
+ pub(crate) const X_CC_VERSION: &str = "X-CC-Version";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index a667c5ddc3c..31052ab0df2 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token {
default_imp_for_authorize_session_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax {
default_imp_for_calculate_tax!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update {
default_imp_for_session_update!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Helcim,
@@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
@@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization {
default_imp_for_incremental_authorization!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer {
default_imp_for_create_customer!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response {
default_imp_for_connector_redirect_response!(
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{
default_imp_for_post_processing_steps!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve {
default_imp_for_approve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject {
default_imp_for_reject!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification {
default_imp_for_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute {
default_imp_for_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence {
default_imp_for_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute {
default_imp_for_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload {
default_imp_for_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create {
default_imp_for_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve {
default_imp_for_payouts_retrieve!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility {
default_imp_for_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill {
default_imp_for_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel {
default_imp_for_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote {
default_imp_for_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient {
default_imp_for_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account {
default_imp_for_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale {
default_imp_for_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout {
default_imp_for_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction {
default_imp_for_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment {
default_imp_for_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return {
default_imp_for_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates {
default_imp_for_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 3bb1abfef21..16e592688ac 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute {
default_imp_for_new_connector_integration_accept_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_submit_evidence!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
default_imp_for_new_connector_integration_payouts_create!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
default_imp_for_new_connector_integration_payouts_quote!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
default_imp_for_new_connector_integration_payouts_sync!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
default_imp_for_new_connector_integration_frm_sale!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
default_imp_for_new_connector_integration_frm_checkout!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
default_imp_for_new_connector_integration_frm_transaction!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
default_imp_for_new_connector_integration_frm_record_return!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
@@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Bambora,
connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Coinbase,
+ connectors::Cryptopay,
connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index b2979975e55..f96d715f5be 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount
use base64::Engine;
use common_enums::{
enums,
- enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
+ enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation},
};
use common_utils::{
consts::BASE64_ENGINE,
@@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>(
.change_context(errors::ConnectorError::AmountConversionFailed)
}
+pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
+ match status {
+ AttemptStatus::AuthenticationFailed
+ | AttemptStatus::AuthorizationFailed
+ | AttemptStatus::CaptureFailed
+ | AttemptStatus::VoidFailed
+ | AttemptStatus::Failure => true,
+ AttemptStatus::Started
+ | AttemptStatus::RouterDeclined
+ | AttemptStatus::AuthenticationPending
+ | AttemptStatus::AuthenticationSuccessful
+ | AttemptStatus::Authorized
+ | AttemptStatus::Charged
+ | AttemptStatus::Authorizing
+ | AttemptStatus::CodInitiated
+ | AttemptStatus::Voided
+ | AttemptStatus::VoidInitiated
+ | AttemptStatus::CaptureInitiated
+ | AttemptStatus::AutoRefunded
+ | AttemptStatus::PartialCharged
+ | AttemptStatus::PartialChargedAndChargeable
+ | AttemptStatus::Unresolved
+ | AttemptStatus::Pending
+ | AttemptStatus::PaymentMethodAwaited
+ | AttemptStatus::ConfirmationAwaited
+ | AttemptStatus::DeviceDataCollectionPending => false,
+ }
+}
+
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
@@ -1460,6 +1489,18 @@ fn get_header_field(
))?
}
+pub trait CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error>;
+}
+
+impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData {
+ fn get_pay_currency(&self) -> Result<String, Error> {
+ self.pay_currency
+ .clone()
+ .ok_or_else(missing_field_err("crypto_data.pay_currency"))
+ }
+}
+
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index b505f8c8c52..116fc67320f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -9,10 +9,7 @@ pub mod billwerk;
pub mod bluesnap;
pub mod boku;
pub mod braintree;
-pub mod cashtocode;
pub mod checkout;
-pub mod coinbase;
-pub mod cryptopay;
pub mod cybersource;
pub mod datatrans;
pub mod dlocal;
@@ -62,12 +59,13 @@ pub mod zen;
pub mod zsl;
pub use hyperswitch_connectors::connectors::{
- bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank,
- fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay,
- globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay,
- nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax,
- stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt,
- worldline, worldline::Worldline,
+ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode,
+ coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank,
+ deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
+ fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie,
+ nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz,
+ stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt,
+ volt::Volt, worldline, worldline::Worldline,
};
#[cfg(feature = "dummy_connector")]
@@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex,
authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica,
- billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
- cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
+ billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout,
cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte,
globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay,
itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay,
diff --git a/crates/router/src/core/payments/connector_integration_v2_impls.rs b/crates/router/src/core/payments/connector_integration_v2_impls.rs
index 041b5bb7359..3ff93cf9bf0 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e364d662e24..f9a6b461a13 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -209,10 +209,7 @@ default_imp_for_complete_authorize!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!(
connector::Bluesnap,
connector::Braintree,
connector::Boku,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -376,10 +370,7 @@ default_imp_for_create_customer!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!(
connector::Bankofamerica,
connector::Billwerk,
connector::Boku,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -630,9 +618,6 @@ default_imp_for_accept_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -739,9 +724,6 @@ default_imp_for_file_upload!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
- connector::Coinbase,
- connector::Cryptopay,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -825,10 +807,7 @@ default_imp_for_submit_evidence!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -911,10 +890,7 @@ default_imp_for_defend_dispute!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Cybersource,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Coinbase,
- connector::Cryptopay,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Forte,
@@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -1946,11 +1892,8 @@ default_imp_for_approve!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2035,11 +1978,8 @@ default_imp_for_reject!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
connector::Cybersource,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
@@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
@@ -3158,10 +3071,7 @@ default_imp_for_session_update!(
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Cybersource,
connector::Datatrans,
connector::Dlocal,
| 2024-09-20T18:00:15Z |
## 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/5629
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials. | d9270ace8ddde16eca8c45ceb79af3e4d815d7cd |
Cryptopay:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \
--data-raw '{
"amount": 300,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_D91HEOHsNOK0OJhfM4yo",
"merchant_id": "merchant_1727096693",
"status": "requires_customer_action",
"amount": 300,
"net_amount": 300,
"amount_capturable": 300,
"amount_received": 300,
"connector": "cryptopay",
"client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N",
"created": "2024-09-23T13:19:07.696Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"name": null,
"email": "guest@example.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1",
"payment_link": null,
"profile_id": "pro_1pHVbwpinQ6kPONiCARj",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-23T13:34:07.695Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-23T13:19:09.657Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials.
| [
"crates/hyperswitch_connectors/src/connectors.rs",
"crates/router/src/connector/cashtocode.rs",
"crates/router/src/connector/cashtocode/transformers.rs",
"crates/router/src/connector/coinbase.rs",
"crates/router/src/connector/coinbase/transformers.rs",
"crates/router/src/connector/cryptopay.rs",
"crates... | |
juspay/hyperswitch | juspay__hyperswitch-5982 | Bug: add `email` in `billing` and `shipping` address of merchant payment method list
This is to extend the feature of [collect address details](https://github.com/juspay/hyperswitch/pull/5418) to collect `billing.email` and `shipping.email`.
As per this when `"always_collect_shipping_details_from_wallet_connector": true` and `"always_collect_billing_details_from_wallet_connector": true`, if payment method is wallet or paylater, and if payment experience is `"payment_experience_type": "invoke_sdk_client"` then merchant pml will contain `billing.email` and `shipping.email` in addition to existing fields. | diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 41efc6e4c38..5719e111759 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -12353,6 +12353,15 @@ pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> {
value: None,
},
),
+ (
+ "billing.email".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ },
+ ),
])
}
@@ -12441,6 +12450,15 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
value: None,
},
),
+ (
+ "shipping.email".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ },
+ ),
])
}
| 2024-09-20T13:48:34Z |
## Description
<!-- Describe your changes in detail -->
This is to extend the feature of [collect address details](https://github.com/juspay/hyperswitch/pull/5418) to collect `billing.email` and `shipping.email`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account
-> Set the below config in the business profile
```
curl --location 'http://localhost:8080/account/merchant_1726839405/business_profile/pro_TwNiv0vtGBct5t1SLyhm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: *' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true
}'
```
```
{
"merchant_id": "merchant_1726839405",
"profile_id": "pro_TwNiv0vtGBct5t1SLyhm",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "ODPObMKINwvWuUGwHgikqYs7XC3jpRpnPpicIK4IFP3flJ3ZeEREOzagzyEHOGTz",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false
}
```
-> Create a connector with wallet or paylater payment method enabled
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726839665"
}'
```
```
{
"payment_id": "pay_mtBJnDsvfQoVztmE4Zl1",
"merchant_id": "merchant_1726839405",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj",
"created": "2024-09-20T13:37:30.990Z",
"currency": "USD",
"customer_id": "cu_1726839451",
"customer": {
"id": "cu_1726839451",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726839451",
"created_at": 1726839450,
"expires": 1726843050,
"secret": "epk_8f8412ffd628422c8c108e8c75cef572"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_TwNiv0vtGBct5t1SLyhm",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-20T13:52:30.990Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-20T13:37:31.050Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Merchant payment method list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj' \
--header 'Accept: application/json' \
--header 'api-key: '
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"klarna"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.phone.number": {
"required_field": "shipping.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.phone.country_code": {
"required_field": "shipping.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.email": {
"required_field": "shipping.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.phone.country_code": {
"required_field": "payment_method_data.billing.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.phone.number": {
"required_field": "payment_method_data.billing.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
``` | c0cac8d9135b14945ce5763327ec16b1578ca2a2 |
-> Create a merchant account
-> Set the below config in the business profile
```
curl --location 'http://localhost:8080/account/merchant_1726839405/business_profile/pro_TwNiv0vtGBct5t1SLyhm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: *' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true
}'
```
```
{
"merchant_id": "merchant_1726839405",
"profile_id": "pro_TwNiv0vtGBct5t1SLyhm",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "ODPObMKINwvWuUGwHgikqYs7XC3jpRpnPpicIK4IFP3flJ3ZeEREOzagzyEHOGTz",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false
}
```
-> Create a connector with wallet or paylater payment method enabled
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726839665"
}'
```
```
{
"payment_id": "pay_mtBJnDsvfQoVztmE4Zl1",
"merchant_id": "merchant_1726839405",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj",
"created": "2024-09-20T13:37:30.990Z",
"currency": "USD",
"customer_id": "cu_1726839451",
"customer": {
"id": "cu_1726839451",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726839451",
"created_at": 1726839450,
"expires": 1726843050,
"secret": "epk_8f8412ffd628422c8c108e8c75cef572"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_TwNiv0vtGBct5t1SLyhm",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-20T13:52:30.990Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-20T13:37:31.050Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Merchant payment method list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj' \
--header 'Accept: application/json' \
--header 'api-key: '
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"klarna"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.phone.number": {
"required_field": "shipping.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.phone.country_code": {
"required_field": "shipping.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.email": {
"required_field": "shipping.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.phone.country_code": {
"required_field": "payment_method_data.billing.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.phone.number": {
"required_field": "payment_method_data.billing.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
```
| [
"crates/router/src/configs/defaults.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5979 | Bug: [REFACTOR] API Key List and Update endpoints in Hyperswitch V2
Update API Key endpoint in V2, the URLs are registered in the `app.rs` but the necessary changes to it has not been made in `api_keys.rs`.
In addition to that, List API Key endpoint for V2 does not work as no such thing exist in `api_keys.rs`.
So at present, when that endpoint is hit, you'll receive a 404 as mentioned below:
```curl
curl --location --request PUT '{{baseUrl}}/v2/api_keys/{{api_key_id}}' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-merchant-id: {{mechant_id}}' \
--header 'api-key: {{admin_api_key}}' \
--data '{
"name": "My new Api Key"
}'
```
```json
wrong number of parameters: 1 expected 2
```
List end point:
```curl
curl --location '{{baseUrl}}/v2/api_keys/list' \
--header 'x-merchant-id: {{mechant_id}}' \
--header 'api-key: {{admin_api_key}}'
```
```json
wrong number of parameters: 0 expected 1
```
I'll be fixing this. | diff --git a/api-reference-v2/api-reference/api-key/api-key--list.mdx b/api-reference-v2/api-reference/api-key/api-key--list.mdx
new file mode 100644
index 00000000000..5975e9bd6ca
--- /dev/null
+++ b/api-reference-v2/api-reference/api-key/api-key--list.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/api_keys/list
+---
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index ae48e2b8e76..08bc5868af0 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -80,7 +80,8 @@
"api-reference/api-key/api-key--create",
"api-reference/api-key/api-key--retrieve",
"api-reference/api-key/api-key--update",
- "api-reference/api-key/api-key--revoke"
+ "api-reference/api-key/api-key--revoke",
+ "api-reference/api-key/api-key--list"
]
},
{
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index fb679970f3d..c60ea81c7b4 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -1433,6 +1433,60 @@
]
}
},
+ "/v2/api_keys/list": {
+ "get": {
+ "tags": [
+ "API Key"
+ ],
+ "summary": "API Key - List",
+ "description": "List all the API Keys associated to a merchant account.",
+ "operationId": "List all API Keys associated with a merchant account",
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "The maximum number of API Keys to include in the response",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int64",
+ "nullable": true
+ }
+ },
+ {
+ "name": "skip",
+ "in": "query",
+ "description": "The number of API Keys to skip when retrieving the list of API keys.",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int64",
+ "nullable": true
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of API Keys retrieved successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/RetrieveApiKeyResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "admin_api_key": []
+ }
+ ]
+ }
+ },
"/v2/customers": {
"post": {
"tags": [
diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs
index 1fc7ce97be8..65cc6b9a25a 100644
--- a/crates/api_models/src/api_keys.rs
+++ b/crates/api_models/src/api_keys.rs
@@ -154,7 +154,7 @@ pub struct RevokeApiKeyResponse {
}
/// The constraints that are applicable when listing API Keys associated with a merchant account.
-#[derive(Clone, Debug, Deserialize)]
+#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ListApiKeyConstraints {
/// The maximum number of API Keys to include in the response.
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index b8a872ffd25..5816df518bd 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -90,6 +90,7 @@ impl_api_event_type!(
CardInfoResponse,
CreateApiKeyResponse,
CreateApiKeyRequest,
+ ListApiKeyConstraints,
MerchantConnectorDeleteResponse,
MerchantConnectorUpdate,
MerchantConnectorCreate,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 85865584494..ae999bb0604 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -183,6 +183,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
+ routes::api_keys::api_key_list,
// Routes for events
routes::webhook_events::list_initial_webhook_delivery_attempts,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 05fded520f0..ae9818ddee6 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -109,6 +109,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
+ routes::api_keys::api_key_list,
//Routes for customers
routes::customers::customers_create,
diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs
index 7ed2afe91a1..7527c8a1095 100644
--- a/crates/openapi/src/routes/api_keys.rs
+++ b/crates/openapi/src/routes/api_keys.rs
@@ -163,3 +163,44 @@ pub async fn api_key_revoke() {}
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
+
+#[cfg(feature = "v1")]
+/// API Key - List
+///
+/// List all the API Keys associated to a merchant account.
+#[utoipa::path(
+ get,
+ path = "/api_keys/{merchant_id}/list",
+ params(
+ ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
+ ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
+ ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
+ ),
+ responses(
+ (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
+ ),
+ tag = "API Key",
+ operation_id = "List all API Keys associated with a merchant account",
+ security(("admin_api_key" = []))
+)]
+pub async fn api_key_list() {}
+
+#[cfg(feature = "v2")]
+/// API Key - List
+///
+/// List all the API Keys associated to a merchant account.
+#[utoipa::path(
+ get,
+ path = "/v2/api_keys/list",
+ params(
+ ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
+ ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
+ ),
+ responses(
+ (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
+ ),
+ tag = "API Key",
+ operation_id = "List all API Keys associated with a merchant account",
+ security(("admin_api_key" = []))
+)]
+pub async fn api_key_list() {}
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index a00e740b3e6..047e0d9b886 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -9,10 +9,6 @@ use crate::{
types::api as api_types,
};
-/// API Key - Create
-///
-/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
-/// displayed only once on creation, so ensure you store it securely.
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))]
pub async fn api_key_create(
@@ -78,9 +74,6 @@ pub async fn api_key_create(
.await
}
-/// API Key - Retrieve
-///
-/// Retrieve information about the specified API Key.
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))]
pub async fn api_key_retrieve(
@@ -117,9 +110,6 @@ pub async fn api_key_retrieve(
}
#[cfg(feature = "v1")]
-/// API Key - Retrieve
-///
-/// Retrieve information about the specified API Key.
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))]
pub async fn api_key_retrieve(
state: web::Data<AppState>,
@@ -150,9 +140,6 @@ pub async fn api_key_retrieve(
}
#[cfg(feature = "v1")]
-/// API Key - Update
-///
-/// Update information for the specified API Key.
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))]
pub async fn api_key_update(
state: web::Data<AppState>,
@@ -190,26 +177,27 @@ pub async fn api_key_update(
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(common_utils::id_type::MerchantId, String)>,
+ key_id: web::Path<String>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
- let (merchant_id, key_id) = path.into_inner();
+ let api_key_id = key_id.into_inner();
let mut payload = json_payload.into_inner();
- payload.key_id = key_id;
- payload.merchant_id.clone_from(&merchant_id);
+ payload.key_id = api_key_id;
api::server_wrap(
flow,
state,
&req,
payload,
- |state, _, payload, _| api_keys::update_api_key(state, payload),
+ |state, authentication_data, mut payload, _| {
+ payload.merchant_id = authentication_data.merchant_account.get_id().to_owned();
+ api_keys::update_api_key(state, payload)
+ },
auth::auth_type(
- &auth::AdminApiAuth,
- &auth::JWTAuthMerchantFromRoute {
- merchant_id,
- required_permission: Permission::ApiKeyWrite,
+ &auth::AdminApiAuthWithMerchantIdFromHeader,
+ &auth::JWTAuthMerchantFromHeader {
+ required_permission: Permission::ApiKeyRead,
minimum_entity_level: EntityType::Merchant,
},
req.headers(),
@@ -220,10 +208,6 @@ pub async fn api_key_update(
}
#[cfg(feature = "v1")]
-/// API Key - Revoke
-///
-/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
-/// authenticating with our APIs.
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))]
pub async fn api_key_revoke(
state: web::Data<AppState>,
@@ -283,24 +267,7 @@ pub async fn api_key_revoke(
.await
}
-/// API Key - List
-///
-/// List all API Keys associated with your merchant account.
-#[utoipa::path(
- get,
- path = "/api_keys/{merchant_id}/list",
- params(
- ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
- ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
- ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
- ),
- responses(
- (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
- ),
- tag = "API Key",
- operation_id = "List all API Keys associated with a merchant account",
- security(("admin_api_key" = []))
-)]
+#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))]
pub async fn api_key_list(
state: web::Data<AppState>,
@@ -335,3 +302,34 @@ pub async fn api_key_list(
)
.await
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))]
+pub async fn api_key_list(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_types::ListApiKeyConstraints>,
+) -> impl Responder {
+ let flow = Flow::ApiKeyList;
+ let payload = query.into_inner();
+
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, authentication_data, payload, _| async move {
+ let merchant_id = authentication_data.merchant_account.get_id().to_owned();
+ api_keys::list_api_keys(state, merchant_id, payload.limit, payload.skip).await
+ },
+ auth::auth_type(
+ &auth::AdminApiAuthWithMerchantIdFromHeader,
+ &auth::JWTAuthMerchantFromHeader {
+ required_permission: Permission::ApiKeyRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
| 2024-09-20T13:18:13Z |
## Description
<!-- Describe your changes in detail -->
This PR fixes `404` errors thrown by API Key List and Update endpoints.
Previously:
Update end point:
```curl
curl --location --request PUT '{{baseUrl}}/v2/api_keys/{{api_key_id}}' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-merchant-id: {{mechant_id}}' \
--header 'api-key: {{admin_api_key}}' \
--data '{
"name": "My new Api Key"
}'
```
```json
wrong number of parameters: 1 expected 2
```
List end point:
```curl
curl --location '{{baseUrl}}/v2/api_keys/list' \
--header 'x-merchant-id: {{mechant_id}}' \
--header 'api-key: {{admin_api_key}}'
```
```json
wrong number of parameters: 0 expected 1
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
endpoints under `v2` flags were not properly handled in `api_keys.rs` file and this PR fixes that.
closes #5979
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
tested it by running locally.
Create Api Key endpoint:
```curl
curl --location 'http://Localhost:8080/v2/api_keys' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"name": "My Api Key",
"expiration": "never"
}'
```
```json
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"api_key": "dev_N0jTf3lRHljowpMGs9IKTPhOYkZXY3Sca8kUpSR5DbtjxaBvfqMIqshU5hx81AJp",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
```
Update Api Key endpoint:
```curl
curl --location --request PUT 'http://Localhost:8080/v2/api_keys/dev_xhm09vaThZEPcxuZMJOG' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'api-key: test_admin' \
--data '{
"name": "My new Api Key"
}'
```
```json
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My new Api Key",
"description": null,
"prefix": "dev_N0jTf3lR",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
```
List Api Keys endpoint:
```curl
curl --location 'http://Localhost:8080/v2/api_keys/list' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'api-key: test_admin'
```
```json
[
{
"key_id": "dev_X8F7qFGnO9a1IGIrtuzb",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_8jfmSMnn",
"created": "2024-09-20T13:02:57.150Z",
"expiration": "never"
},
{
"key_id": "dev_F8TDC9bHerHzYdiql80m",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_g8SO3blK",
"created": "2024-09-20T13:02:57.815Z",
"expiration": "never"
},
{
"key_id": "dev_DQ3C3DdFczazUFNc6n0i",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_GnLRtXQm",
"created": "2024-09-20T13:02:58.361Z",
"expiration": "never"
},
{
"key_id": "dev_kdISpxDQBmMpJ8BQuGmH",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_h34nUAh4",
"created": "2024-09-20T13:02:58.796Z",
"expiration": "never"
},
{
"key_id": "dev_WBHT3v4SlWcU4R3R8Wt2",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_v5jdBEFo",
"created": "2024-09-20T13:02:59.806Z",
"expiration": "never"
},
{
"key_id": "dev_qiwCmtE8Lbj24uJYC1wQ",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_WRaLVEGq",
"created": "2024-09-20T13:03:00.335Z",
"expiration": "never"
},
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My new Api Key",
"description": null,
"prefix": "dev_N0jTf3lR",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
]
``` | 5fec99b58b0062dbc02fc8fdc1bd8d949d76c51e |
tested it by running locally.
Create Api Key endpoint:
```curl
curl --location 'http://Localhost:8080/v2/api_keys' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"name": "My Api Key",
"expiration": "never"
}'
```
```json
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"api_key": "dev_N0jTf3lRHljowpMGs9IKTPhOYkZXY3Sca8kUpSR5DbtjxaBvfqMIqshU5hx81AJp",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
```
Update Api Key endpoint:
```curl
curl --location --request PUT 'http://Localhost:8080/v2/api_keys/dev_xhm09vaThZEPcxuZMJOG' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'api-key: test_admin' \
--data '{
"name": "My new Api Key"
}'
```
```json
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My new Api Key",
"description": null,
"prefix": "dev_N0jTf3lR",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
```
List Api Keys endpoint:
```curl
curl --location 'http://Localhost:8080/v2/api_keys/list' \
--header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \
--header 'api-key: test_admin'
```
```json
[
{
"key_id": "dev_X8F7qFGnO9a1IGIrtuzb",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_8jfmSMnn",
"created": "2024-09-20T13:02:57.150Z",
"expiration": "never"
},
{
"key_id": "dev_F8TDC9bHerHzYdiql80m",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_g8SO3blK",
"created": "2024-09-20T13:02:57.815Z",
"expiration": "never"
},
{
"key_id": "dev_DQ3C3DdFczazUFNc6n0i",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_GnLRtXQm",
"created": "2024-09-20T13:02:58.361Z",
"expiration": "never"
},
{
"key_id": "dev_kdISpxDQBmMpJ8BQuGmH",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_h34nUAh4",
"created": "2024-09-20T13:02:58.796Z",
"expiration": "never"
},
{
"key_id": "dev_WBHT3v4SlWcU4R3R8Wt2",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_v5jdBEFo",
"created": "2024-09-20T13:02:59.806Z",
"expiration": "never"
},
{
"key_id": "dev_qiwCmtE8Lbj24uJYC1wQ",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My Api Key",
"description": null,
"prefix": "dev_WRaLVEGq",
"created": "2024-09-20T13:03:00.335Z",
"expiration": "never"
},
{
"key_id": "dev_xhm09vaThZEPcxuZMJOG",
"merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae",
"name": "My new Api Key",
"description": null,
"prefix": "dev_N0jTf3lR",
"created": "2024-09-20T13:03:00.859Z",
"expiration": "never"
}
]
```
| [
"api-reference-v2/api-reference/api-key/api-key--list.mdx",
"api-reference-v2/mint.json",
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/api_keys.rs",
"crates/api_models/src/events.rs",
"crates/openapi/src/openapi.rs",
"crates/openapi/src/openapi_v2.rs",
"crates/openapi/src/routes/api_ke... | |
juspay/hyperswitch | juspay__hyperswitch-5976 | Bug: [BUG] [DEUTSCHEBANK] Trim the spaces in IBAN
### Bug Description
Trim the spaces in IBAN before sending it in SEPA Mandate Post and Direct Debit requests for Deutsche Bank.
### Expected Behavior
No spaces in IBAN in SEPA Mandate Post and Direct Debit requests.
### Actual Behavior
Spaces in IBAN in SEPA Mandate Post and Direct Debit requests.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
index 8b3837edd63..30b1d65134a 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
@@ -155,7 +155,7 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
Ok(Self::MandatePost(DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval::Click,
email_address: item.router_data.request.get_email()?,
- iban,
+ iban: Secret::from(iban.peek().replace(" ", "")),
first_name: billing_address.get_first_name()?.clone(),
last_name: billing_address.get_last_name()?.clone(),
}))
@@ -313,7 +313,7 @@ impl
PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
iban,
..
- }) => Ok(iban),
+ }) => Ok(Secret::from(iban.peek().replace(" ", ""))),
_ => Err(errors::ConnectorError::MissingRequiredField {
field_name:
"payment_method_data.bank_debit.sepa_bank_debit.iban"
@@ -470,7 +470,7 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
means_of_payment: DeutschebankMeansOfPayment {
bank_account: DeutschebankBankAccount {
account_holder,
- iban,
+ iban: Secret::from(iban.peek().replace(" ", "")),
},
},
mandate: {
| 2024-09-20T11:49:40Z |
## Description
<!-- Describe your changes in detail -->
Trim the spaces in IBAN before sending it in SEPA Mandate Post and Direct Debit requests for Deutsche Bank.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/5976
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 9000,
"currency": "EUR",
"confirm": true,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87 1234 5678 1234 5678 90"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "doe"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
},
"setup_future_usage": "off_session"
}'
```
Response:
```
{
"payment_id": "pay_THxTbiKwV1xv7Tmkqe8I",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 9000,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_THxTbiKwV1xv7Tmkqe8I_secret_hx91jywe0lywBW5UrLb0",
"created": "2024-09-20T11:05:32.884Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE87 **** **** **** **78 90",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_LBU2etjaOq7pdJhAPHMk",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_THxTbiKwV1xv7Tmkqe8I/merchant_1725539597/pay_THxTbiKwV1xv7Tmkqe8I_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726830332,
"expires": 1726833932,
"secret": "epk_fb2f1bbac4204fc2841fd2b74a295fa0"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-20T11:20:32.884Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_R9MnbGoavSYoxTmxMiS2",
"payment_method_status": null,
"updated": "2024-09-20T11:05:35.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
``` | 5335f2d21ce6f0c11dc84fd56b3cd2c80e8b064f |
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 9000,
"currency": "EUR",
"confirm": true,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87 1234 5678 1234 5678 90"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "doe"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
},
"setup_future_usage": "off_session"
}'
```
Response:
```
{
"payment_id": "pay_THxTbiKwV1xv7Tmkqe8I",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 9000,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_THxTbiKwV1xv7Tmkqe8I_secret_hx91jywe0lywBW5UrLb0",
"created": "2024-09-20T11:05:32.884Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE87 **** **** **** **78 90",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_LBU2etjaOq7pdJhAPHMk",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_THxTbiKwV1xv7Tmkqe8I/merchant_1725539597/pay_THxTbiKwV1xv7Tmkqe8I_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726830332,
"expires": 1726833932,
"secret": "epk_fb2f1bbac4204fc2841fd2b74a295fa0"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-20T11:20:32.884Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_R9MnbGoavSYoxTmxMiS2",
"payment_method_status": null,
"updated": "2024-09-20T11:05:35.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
| [
"crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5974 | Bug: Missing terms and conditions for the contests.
The team should add terms and conditions for the contests like Hacktoberfest. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 926af8c162c..577fe4ae1b7 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -7293,7 +7293,7 @@
},
"FutureUsage": {
"type": "string",
- "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.",
+ "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\n- On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment\n- Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.",
"enum": [
"off_session",
"on_session"
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 31cb43669b2..bd1cd36f8bd 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1357,6 +1357,8 @@ pub enum IntentStatus {
}
/// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.
+/// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment
+/// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.
#[derive(
Clone,
Copy,
| 2024-09-20T10:51:26Z |
## 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 this - #5974
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
--> | dccb8d4e629d615a69f6922a96e72f10d3410bfc | [
"api-reference-v2/openapi_spec.json",
"crates/common_enums/src/enums.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-5970 | Bug: add `phone` and `country_code` in dynamic fields
This is to extend the feature of [collecting address details](https://github.com/juspay/hyperswitch/pull/5418) from wallets to paylater.
Additionally also include phone and country_code in the dynamic fields. | diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 4fcb0785ea1..41efc6e4c38 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -12335,6 +12335,24 @@ pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> {
value: None,
},
),
+ (
+ "billing.phone.number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.phone.number".to_string(),
+ display_name: "phone_number".to_string(),
+ field_type: enums::FieldType::UserPhoneNumber,
+ value: None,
+ },
+ ),
+ (
+ "billing.phone.country_code".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.phone.country_code".to_string(),
+ display_name: "dialing_code".to_string(),
+ field_type: enums::FieldType::UserPhoneNumberCountryCode,
+ value: None,
+ },
+ ),
])
}
@@ -12405,6 +12423,24 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> {
value: None,
},
),
+ (
+ "shipping.phone.number".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.phone.number".to_string(),
+ display_name: "phone_number".to_string(),
+ field_type: enums::FieldType::UserPhoneNumber,
+ value: None,
+ },
+ ),
+ (
+ "shipping.phone.country_code".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.phone.country_code".to_string(),
+ display_name: "dialing_code".to_string(),
+ field_type: enums::FieldType::UserPhoneNumberCountryCode,
+ value: None,
+ },
+ ),
])
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 79d1226f13a..7d3742a476d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3840,7 +3840,11 @@ fn should_collect_shipping_or_billing_details_from_wallet_connector(
mut required_fields_hs: HashMap<String, RequiredFieldInfo>,
) -> HashMap<String, RequiredFieldInfo> {
match (payment_method, payment_experience_optional) {
- (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient)) => {
+ (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient))
+ | (
+ api_enums::PaymentMethod::PayLater,
+ Some(api_enums::PaymentExperience::InvokeSdkClient),
+ ) => {
let always_send_billing_details = business_profile.and_then(|business_profile| {
business_profile.always_collect_billing_details_from_wallet_connector
});
| 2024-09-19T14:51:31Z |
## Description
<!-- Describe your changes in detail -->
This is to extend the feature of [collecting address details](https://github.com/juspay/hyperswitch/pull/5418) from wallets to paylater.
Additionally also include phone and country_code in the dynamic fields.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant connector of Klarna with klarna payment method enabled.
-> Set the below business profile config
```
curl --location 'http://localhost:8080/account/merchant_1726764490/business_profile/pro_XOWZOwYWMAmTV4wEyGgh' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ]' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true
}'
```
```
{
"merchant_id": "merchant_1726764490",
"profile_id": "pro_XOWZOwYWMAmTV4wEyGgh",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "cG93fXrQQUtILvsThLoMz2EGwi7b3avGaiEb5NQ2OAbHYbFP2Lx2VigfrdbICkLK",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_EAjkFh4IFwdG0BhppR4qc8duYSjLtl5e2cYy1eADeQ4MAtLazHsE3fpA6wI4cUk9' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726764583"
}'
```
```
{
"payment_id": "pay_66ZCSMDS1OQlfVVzAYNf",
"merchant_id": "merchant_1726764490",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La",
"created": "2024-09-19T16:49:40.260Z",
"currency": "USD",
"customer_id": "cu_1726764580",
"customer": {
"id": "cu_1726764580",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726764580",
"created_at": 1726764580,
"expires": 1726768180,
"secret": "epk_82cd32e8fe0a4190a5db562353a40f33"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XOWZOwYWMAmTV4wEyGgh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T17:04:40.260Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T16:49:40.288Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Merchant payment method list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La' \
--header 'Accept: application/json' \
--header 'api-key:'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"klarna"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.phone.country_code": {
"required_field": "shipping.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.phone.number": {
"required_field": "shipping.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.phone.number": {
"required_field": "payment_method_data.billing.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.phone.country_code": {
"required_field": "payment_method_data.billing.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
``` | 5942e059e9efa3fa71a13cacc896509515e2f976 |
-> Create a merchant connector of Klarna with klarna payment method enabled.
-> Set the below business profile config
```
curl --location 'http://localhost:8080/account/merchant_1726764490/business_profile/pro_XOWZOwYWMAmTV4wEyGgh' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: ]' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true
}'
```
```
{
"merchant_id": "merchant_1726764490",
"profile_id": "pro_XOWZOwYWMAmTV4wEyGgh",
"profile_name": "US_default",
"return_url": "https://google.com/success",
"enable_payment_response_hash": true,
"payment_response_hash_key": "cG93fXrQQUtILvsThLoMz2EGwi7b3avGaiEb5NQ2OAbHYbFP2Lx2VigfrdbICkLK",
"redirect_to_merchant_with_http_post": false,
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"webhook_url": null,
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"metadata": null,
"routing_algorithm": null,
"intent_fulfillment_time": 900,
"frm_routing_algorithm": null,
"payout_routing_algorithm": null,
"applepay_verified_domains": null,
"session_expiry": 900,
"payment_link_config": null,
"authentication_connector_details": null,
"use_billing_as_payment_method_billing": true,
"extended_card_info_config": null,
"collect_shipping_details_from_wallet_connector": false,
"collect_billing_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": false,
"payout_link_config": null,
"outgoing_webhook_custom_http_headers": null,
"tax_connector_id": null,
"is_tax_connector_enabled": false,
"is_network_tokenization_enabled": false
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_EAjkFh4IFwdG0BhppR4qc8duYSjLtl5e2cYy1eADeQ4MAtLazHsE3fpA6wI4cUk9' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726764583"
}'
```
```
{
"payment_id": "pay_66ZCSMDS1OQlfVVzAYNf",
"merchant_id": "merchant_1726764490",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La",
"created": "2024-09-19T16:49:40.260Z",
"currency": "USD",
"customer_id": "cu_1726764580",
"customer": {
"id": "cu_1726764580",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726764580",
"created_at": 1726764580,
"expires": 1726768180,
"secret": "epk_82cd32e8fe0a4190a5db562353a40f33"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XOWZOwYWMAmTV4wEyGgh",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T17:04:40.260Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T16:49:40.288Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Merchant payment method list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La' \
--header 'Accept: application/json' \
--header 'api-key:'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"klarna"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.phone.country_code": {
"required_field": "shipping.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.phone.number": {
"required_field": "shipping.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.phone.number": {
"required_field": "payment_method_data.billing.phone.number",
"display_name": "phone_number",
"field_type": "user_phone_number",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.phone.country_code": {
"required_field": "payment_method_data.billing.phone.country_code",
"display_name": "dialing_code",
"field_type": "user_phone_number_country_code",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
```
| [
"crates/router/src/configs/defaults.rs",
"crates/router/src/core/payment_methods/cards.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5963 | Bug: fix(dashboard_metadata): Fix prod intent emails
Currently prod intent emails are not going to biz email. Email are working on custom integ, integ main pod and custom sandbox pod with some code changes. Need to check if sandbox main pod is also able to send emails. | diff --git a/config/config.example.toml b/config/config.example.toml
index be0532622bb..a6af984b01f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -375,10 +375,12 @@ wildcard_origin = false # If true, allows any origin to make req
# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
[email]
-sender_email = "example@example.com" # Sender email
-aws_region = "" # AWS region used by AWS SES
-allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email
-active_email_client = "SES" # The currently active email client
+sender_email = "example@example.com" # Sender email
+aws_region = "" # AWS region used by AWS SES
+allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email
+active_email_client = "SES" # The currently active email client
+recon_recipient_email = "recon@example.com" # Recipient email for recon request email
+prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email
# Configuration for aws ses, applicable when the active email client is SES
[email.aws_ses]
@@ -745,4 +747,4 @@ delete_token_url= "" # base url to delete token from token service
check_token_status_url= "" # base url to check token status from token service
[network_tokenization_supported_connectors]
-connector_list = "cybersource" # Supported connectors for network tokenization
\ No newline at end of file
+connector_list = "cybersource" # Supported connectors for network tokenization
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 9bbf137d2ce..62350376271 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -60,6 +60,8 @@ sender_email = "example@example.com" # Sender email
aws_region = "" # AWS region used by AWS SES
allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email
active_email_client = "SES" # The currently active email client
+recon_recipient_email = "recon@example.com" # Recipient email for recon request email
+prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email
# Configuration for aws ses, applicable when the active email client is SES
[email.aws_ses]
@@ -300,9 +302,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p
[user_auth_methods]
encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table
-[recipient_emails]
-recon = "recon@example.com"
-
[network_tokenization_service] # Network Tokenization Service Configuration
generate_token_url= "" # base url to generate token
fetch_token_url= "" # base url to fetch token
@@ -311,4 +310,4 @@ public_key= "" # public key to encrypt data for token service
private_key= "" # private key to decrypt response payload from token service
key_id= "" # key id to encrypt data for token service
delete_token_url= "" # base url to delete token from token service
-check_token_status_url= "" # base url to check token status from token service
\ No newline at end of file
+check_token_status_url= "" # base url to check token status from token service
diff --git a/config/development.toml b/config/development.toml
index f9f1ebc1202..43130cb78f2 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -301,6 +301,8 @@ sender_email = "example@example.com"
aws_region = ""
allowed_unverified_days = 1
active_email_client = "SES"
+recon_recipient_email = "recon@example.com"
+prod_intent_recipient_email = "business@example.com"
[email.aws_ses]
email_role_arn = ""
@@ -732,11 +734,8 @@ encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC69
[locker_based_open_banking_connectors]
connector_list = ""
-[recipient_emails]
-recon = "recon@example.com"
-
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
[network_tokenization_supported_connectors]
-connector_list = "cybersource"
\ No newline at end of file
+connector_list = "cybersource"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 698800f082d..379f491a4f6 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -591,9 +591,6 @@ ach = { country = "US", currency = "USD" }
[locker_based_open_banking_connectors]
connector_list = ""
-[recipient_emails]
-recon = "recon@example.com"
-
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
@@ -609,3 +606,17 @@ check_token_status_url= ""
[network_tokenization_supported_connectors]
connector_list = "cybersource"
+
+# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
+[email]
+sender_email = "example@example.com" # Sender email
+aws_region = "" # AWS region used by AWS SES
+allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email
+active_email_client = "SES" # The currently active email client
+recon_recipient_email = "recon@example.com" # Recipient email for recon request email
+prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email
+
+# Configuration for aws ses, applicable when the active email client is SES
+[email.aws_ses]
+email_role_arn = "" # The amazon resource name ( arn ) of the role which has permission to send emails
+sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs
index fc577a012c3..5751de95c12 100644
--- a/crates/external_services/src/email.rs
+++ b/crates/external_services/src/email.rs
@@ -137,6 +137,12 @@ pub struct EmailSettings {
/// The active email client to use
pub active_email_client: AvailableEmailClients,
+
+ /// Recipient email for recon emails
+ pub recon_recipient_email: pii::Email,
+
+ /// Recipient email for recon emails
+ pub prod_intent_recipient_email: pii::Email,
}
/// Errors that could occur from EmailClient.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 604dce5047c..8c893b88319 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -498,7 +498,6 @@ pub(crate) async fn fetch_raw_secrets(
decision: conf.decision,
locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
grpc_client: conf.grpc_client,
- recipient_emails: conf.recipient_emails,
network_tokenization_supported_card_networks: conf
.network_tokenization_supported_card_networks,
network_tokenization_service,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7d6dfd26eae..675b8c44e2a 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -6,7 +6,7 @@ use std::{
#[cfg(feature = "olap")]
use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::{enums, payment_methods::RequiredFieldInfo};
-use common_utils::{ext_traits::ConfigExt, pii::Email};
+use common_utils::ext_traits::ConfigExt;
use config::{Environment, File};
use error_stack::ResultExt;
#[cfg(feature = "email")]
@@ -122,7 +122,6 @@ pub struct Settings<S: SecretState> {
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
pub grpc_client: GrpcClientSettings,
- pub recipient_emails: RecipientMails,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
@@ -941,11 +940,6 @@ pub struct ServerTls {
pub certificate: PathBuf,
}
-#[derive(Debug, Deserialize, Clone, Default)]
-pub struct RecipientMails {
- pub recon: Email,
-}
-
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 1a2b2ef60a4..6ac2b08e6bb 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -5,7 +5,6 @@ pub const MAX_NAME_LENGTH: usize = 70;
/// The max length of company name and merchant should be same
/// because we are deriving the merchant name from company name
pub const MAX_COMPANY_NAME_LENGTH: usize = MAX_ALLOWED_MERCHANT_NAME_LENGTH;
-pub const BUSINESS_EMAIL: &str = "neeraj.kumar@juspay.in";
pub const RECOVERY_CODES_COUNT: usize = 8;
pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs
index fa9944ee8ee..55ec8cea7a9 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -34,7 +34,7 @@ pub async fn send_recon_request(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert recipient's email to UserEmail")?,
recipient_email: domain::UserEmail::from_pii_email(
- state.conf.recipient_emails.recon.clone(),
+ state.conf.email.recon_recipient_email.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert recipient's email to UserEmail")?,
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index 47639fed717..32ad135a7d6 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -484,7 +484,7 @@ async fn insert_metadata(
state.conf.proxy.https_url.as_ref(),
)
.await;
- logger::info!(?send_email_result);
+ logger::info!(prod_intent_email=?send_email_result);
}
}
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 35bc9f06d9a..1c4ce79ac8c 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -413,9 +413,9 @@ pub struct BizEmailProd {
impl BizEmailProd {
pub fn new(state: &SessionState, data: ProdIntent) -> UserResult<Self> {
Ok(Self {
- recipient_email: (domain::UserEmail::new(
- consts::user::BUSINESS_EMAIL.to_string().into(),
- ))?,
+ recipient_email: domain::UserEmail::from_pii_email(
+ state.conf.email.prod_intent_recipient_email.clone(),
+ )?,
settings: state.conf.clone(),
subject: "New Prod Intent",
user_name: data.poc_name.unwrap_or_default().into(),
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index 5814f64f759..3abdfdd3abe 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -1,4 +1,4 @@
-use std::{net::IpAddr, str::FromStr};
+use std::{net::IpAddr, ops::Not, str::FromStr};
use actix_web::http::header::HeaderMap;
use api_models::user::dashboard_metadata::{
@@ -11,6 +11,7 @@ use diesel_models::{
};
use error_stack::{report, ResultExt};
use masking::Secret;
+use router_env::logger;
use crate::{
core::errors::{UserErrors, UserResult},
@@ -284,8 +285,16 @@ fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> boo
}
pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool {
- not_contains_string(&data.poc_email, "juspay")
- && not_contains_string(&data.business_website, "juspay")
- && not_contains_string(&data.business_website, "hyperswitch")
- && not_contains_string(&Some(user_email), "juspay")
+ let poc_email_check = not_contains_string(&data.poc_email, "juspay");
+ let business_website_check = not_contains_string(&data.business_website, "juspay")
+ && not_contains_string(&data.business_website, "hyperswitch");
+ let user_email_check = not_contains_string(&Some(user_email), "juspay");
+
+ if (poc_email_check && business_website_check && user_email_check).not() {
+ logger::info!(prod_intent_email = poc_email_check);
+ logger::info!(prod_intent_email = business_website_check);
+ logger::info!(prod_intent_email = user_email_check);
+ }
+
+ poc_email_check && business_website_check && user_email_check
}
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index ed15e8893bd..82a21f9fc9c 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -368,5 +368,15 @@ global_tenant = { schema = "public", redis_key_prefix = "" }
[multitenancy.tenants]
public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
-[recipient_emails]
-recon = "recon@example.com"
+[email]
+sender_email = "example@example.com"
+aws_region = ""
+allowed_unverified_days = 1
+active_email_client = "SES"
+recon_recipient_email = "recon@example.com"
+prod_intent_recipient_email = "business@example.com"
+
+[email.aws_ses]
+email_role_arn = ""
+sts_role_session_name = ""
+
| 2024-09-19T12:17:46Z |
## Description
<!-- Describe your changes in detail -->
- This PR add recipient emails for recon and prod_intent under email config.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
`config/config.example.toml`
`config/deployments/env_specific.toml`
`config/development.toml`
`config/docker_compose.toml`
`loadtest/config/development.toml`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5963.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/data' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '
{
"ProdIntent": {
"is_completed": true,
"legal_business_name": "test",
"business_label": "test",
"business_location": "US",
"display_name": "test",
"poc_email": "test",
"business_type": "test",
"business_identifier": "test",
"business_website": "test",
"poc_name": "test",
"poc_contact": "test",
"comments": "test"
}
}
'
```
The above API should send prod intent email to configured prod intent email. | 82574c0e8e7eb69e9f21eedc765145c724960cd5 |
```
curl --location 'http://localhost:8080/user/data' \
--header 'Content-Type: application/json' \
--header 'Authorization: ••••••' \
--data '
{
"ProdIntent": {
"is_completed": true,
"legal_business_name": "test",
"business_label": "test",
"business_location": "US",
"display_name": "test",
"poc_email": "test",
"business_type": "test",
"business_identifier": "test",
"business_website": "test",
"poc_name": "test",
"poc_contact": "test",
"comments": "test"
}
}
'
```
The above API should send prod intent email to configured prod intent email.
| [
"config/config.example.toml",
"config/deployments/env_specific.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/external_services/src/email.rs",
"crates/router/src/configs/secrets_transformers.rs",
"crates/router/src/configs/settings.rs",
"crates/router/src/consts/user.rs",
"c... | |
juspay/hyperswitch | juspay__hyperswitch-5958 | Bug: fix: add time_range constraint to retrieve payment attempt list
Currently, to retrieve the total count for payments, we use a query that gets the total count of attempts based on the last active attempt ID. To enhance performance, we need to add a time_range to the query. This will ensure that the query is executed only for the given time constraint, improving efficiency by narrowing the search to a specific time period. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 5465d902388..3690bcf24db 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -18569,6 +18569,7 @@
},
"TimeRange": {
"type": "object",
+ "description": "A type representing a range of time for filtering, including a mandatory start time and an optional end time.",
"required": [
"start_time"
],
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
index 401c606ccf9..dd1aa3c1bbd 100644
--- a/crates/analytics/src/disputes/metrics.rs
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -4,15 +4,11 @@ mod total_dispute_lost_amount;
use std::collections::HashSet;
-use api_models::{
- analytics::{
- disputes::{
- DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier,
- },
- Granularity,
- },
- payments::TimeRange,
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
+ Granularity,
};
+use common_utils::types::TimeRange;
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 7486ab50a51..e0235c67bed 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -1,10 +1,12 @@
use api_models::{
analytics::search::SearchIndex,
errors::types::{ApiError, ApiErrorResponse},
- payments::TimeRange,
};
use aws_config::{self, meta::region::RegionProviderChain, Region};
-use common_utils::errors::{CustomResult, ErrorSwitch};
+use common_utils::{
+ errors::{CustomResult, ErrorSwitch},
+ types::TimeRange,
+};
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use opensearch::{
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 7abef472068..0379ec09547 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -1,5 +1,6 @@
use std::collections::HashSet;
+pub use common_utils::types::TimeRange;
use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo};
use masking::Secret;
@@ -14,8 +15,6 @@ use self::{
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
};
-pub use crate::payments::TimeRange;
-
pub mod active_payments;
pub mod api_event;
pub mod auth_events;
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index b962f60cae0..24dd0effcbb 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -1,9 +1,7 @@
-use common_utils::hashing::HashedString;
+use common_utils::{hashing::HashedString, types::TimeRange};
use masking::WithType;
use serde_json::Value;
-use crate::payments::TimeRange;
-
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 13966c464d5..41e958cb3f4 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -39,8 +39,6 @@ use crate::{
verifications::*,
};
-impl ApiEventMetric for TimeRange {}
-
impl ApiEventMetric for GetPaymentIntentFiltersRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Analytics)
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 715bf3c3544..b0866cfb265 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4204,7 +4204,7 @@ pub struct PaymentListFilterConstraints {
pub amount_filter: Option<AmountFilter>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
- pub time_range: Option<TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payments list
pub connector: Option<Vec<api_enums::Connector>>,
/// The list of currencies to filter payments list
@@ -4295,20 +4295,6 @@ pub enum SortBy {
Desc,
}
-#[derive(
- Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
-)]
-pub struct TimeRange {
- /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
- #[serde(with = "common_utils::custom_serde::iso8601")]
- #[serde(alias = "startTime")]
- pub start_time: PrimitiveDateTime,
- /// The end time to filter payments list or to get list of filters. If not passed the default time is now
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- #[serde(alias = "endTime")]
- pub end_time: Option<PrimitiveDateTime>,
-}
-
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)]
pub struct VerifyResponse {
pub verify_id: Option<id_type::PaymentId>,
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 10771df4ccd..34e1bbe5449 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -704,7 +704,7 @@ pub struct PayoutListConstraints {
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
#[schema(value_type = Option<TimeRange>)]
- pub time_range: Option<payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
@@ -732,7 +732,7 @@ pub struct PayoutListFilterConstraints {
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
#[schema(value_type = Option<TimeRange>)]
- pub time_range: Option<payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payouts list
#[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))]
pub connector: Option<Vec<api_enums::PayoutConnectors>>,
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index edc0e75bdf2..237a903d80c 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -1,12 +1,12 @@
use std::collections::HashMap;
-use common_utils::pii;
pub use common_utils::types::{ChargeRefunds, MinorUnit};
+use common_utils::{pii, types::TimeRange};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
-use super::payments::{AmountFilter, TimeRange};
+use super::payments::AmountFilter;
use crate::{
admin::{self, MerchantConnectorInfo},
enums,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 16d0fd9b30a..2b1571617e8 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -1,7 +1,7 @@
use common_enums::{PaymentMethod, PaymentMethodType};
use serde::Serialize;
-use crate::id_type;
+use crate::{id_type, types::TimeRange};
pub trait ApiEventMetric {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -139,3 +139,5 @@ impl<T: ApiEventMetric> ApiEventMetric for &T {
T::get_api_event_type(self)
}
}
+
+impl ApiEventMetric for TimeRange {}
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 6acf5000ced..2206744ef0b 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -28,6 +28,7 @@ use rust_decimal::{
};
use semver::Version;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
+use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
@@ -582,6 +583,21 @@ impl StringMajorUnit {
}
}
+/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
+#[derive(
+ Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
+)]
+pub struct TimeRange {
+ /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
+ #[serde(with = "crate::custom_serde::iso8601")]
+ #[serde(alias = "startTime")]
+ pub start_time: PrimitiveDateTime,
+ /// The end time to filter payments list or to get list of filters. If not passed the default time is now
+ #[serde(default, with = "crate::custom_serde::iso8601::option")]
+ #[serde(alias = "endTime")]
+ pub end_time: Option<PrimitiveDateTime>,
+}
+
#[cfg(test)]
mod amount_conversion_tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index fa80b0990d1..48941330ec6 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -351,6 +351,7 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
@@ -360,6 +361,14 @@ impl PaymentAttempt {
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
+ if let Some(time_range) = time_range {
+ filter = filter.filter(dsl::created_at.ge(time_range.start_time));
+
+ if let Some(end_time) = time_range.end_time {
+ filter = filter.filter(dsl::created_at.le(end_time));
+ }
+ }
+
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 24a79e2905e..003509b2039 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -156,6 +156,7 @@ pub trait PaymentAttemptInterface {
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index f5b719fe370..619ebcce68a 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -94,7 +94,7 @@ pub trait PaymentIntentInterface {
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>;
@@ -108,7 +108,7 @@ pub trait PaymentIntentInterface {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>;
#[cfg(all(
@@ -1458,8 +1458,8 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
}
}
-impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints {
- fn from(value: api_models::payments::TimeRange) -> Self {
+impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
+ fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PaymentIntentListParams {
offset: 0,
starting_at: Some(value.start_time),
diff --git a/crates/hyperswitch_domain_models/src/payouts.rs b/crates/hyperswitch_domain_models/src/payouts.rs
index 952028fab30..8c6d751ebec 100644
--- a/crates/hyperswitch_domain_models/src/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts.rs
@@ -52,8 +52,8 @@ impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints
}
}
-impl From<api_models::payments::TimeRange> for PayoutFetchConstraints {
- fn from(value: api_models::payments::TimeRange) -> Self {
+impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
+ fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: Some(value.start_time),
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 42037c3c2d9..eb43089e448 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -67,7 +67,7 @@ pub trait PayoutsInterface {
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
index 3b3a79407d0..4016754510a 100644
--- a/crates/hyperswitch_domain_models/src/refunds.rs
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -6,7 +6,7 @@ pub struct RefundListConstraints {
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub limit: Option<i64>,
pub offset: Option<i64>,
- pub time_range: Option<api_models::payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b626b7d4418..d1746a63dde 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -194,6 +194,7 @@ Never share your secret api keys. Keep them guarded and secure.
),
components(schemas(
common_utils::types::MinorUnit,
+ common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
api_models::refunds::RefundRequest,
@@ -466,7 +467,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::refunds::RefundAggregateResponse,
- api_models::payments::TimeRange,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index f12d6a7b567..b7771dc5e0a 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -119,6 +119,7 @@ Never share your secret api keys. Keep them guarded and secure.
),
components(schemas(
common_utils::types::MinorUnit,
+ common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
api_models::refunds::RefundRequest,
@@ -392,7 +393,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::refunds::RefundAggregateResponse,
- api_models::payments::TimeRange,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index ff5936fc296..30b73eb4c6a 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -516,7 +516,7 @@ pub async fn get_aggregates_for_disputes(
state: SessionState,
merchant: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<dispute_models::DisputesAggregateResponse> {
let db = state.store.as_ref();
let dispute_status_with_count = db
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 30d619efedc..b8255cfcfe5 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3108,6 +3108,7 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
+ constraints.time_range,
pi_fetch_constraints.get_profile_id_list(),
merchant.storage_scheme,
)
@@ -3128,7 +3129,7 @@ pub async fn get_filters_for_payments(
state: SessionState,
merchant: domain::MerchantAccount,
merchant_key_store: domain::MerchantKeyStore,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentListFilters> {
let db = state.store.as_ref();
let pi = db
@@ -3249,7 +3250,7 @@ pub async fn get_aggregates_for_payments(
state: SessionState,
merchant: domain::MerchantAccount,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentsAggregateResponse> {
let db = state.store.as_ref();
let intent_status_with_count = db
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index d0c0b2d3cde..c160acb50c2 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -996,7 +996,7 @@ pub async fn payouts_list_available_filters_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
_locale: &str,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 0f7abf44b14..118f4b81766 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -904,7 +904,7 @@ pub async fn refund_list(
pub async fn refund_filter_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
- req: api_models::payments::TimeRange,
+ req: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundListMetaData> {
let db = state.store;
let filter_list = db
@@ -1098,7 +1098,7 @@ pub async fn get_filters_for_refunds(
pub async fn get_aggregates_for_refunds(
state: SessionState,
merchant: domain::MerchantAccount,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundAggregateResponse> {
let db = state.store.as_ref();
let refund_status_with_count = db
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 1d45cfd405f..a44528fde43 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -52,7 +52,7 @@ pub trait DisputeInterface {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>;
}
@@ -141,7 +141,7 @@ impl DisputeInterface for Store {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::get_dispute_status_with_count(
@@ -390,7 +390,7 @@ impl DisputeInterface for MockDb {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 394c48c1cd8..9b51946c5c4 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -634,7 +634,7 @@ impl DisputeInterface for KafkaStore {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_dispute_status_with_count(merchant_id, profile_id_list, time_range)
@@ -1605,6 +1605,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
@@ -1617,6 +1618,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
+ time_range,
profile_id_list,
storage_scheme,
)
@@ -1750,7 +1752,7 @@ impl PaymentIntentInterface for KafkaStore {
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> {
@@ -1770,7 +1772,7 @@ impl PaymentIntentInterface for KafkaStore {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> {
self.diesel_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
@@ -2233,7 +2235,7 @@ impl PayoutsInterface for KafkaStore {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
self.diesel_store
@@ -2532,7 +2534,7 @@ impl RefundInterface for KafkaStore {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
self.diesel_store
@@ -2544,7 +2546,7 @@ impl RefundInterface for KafkaStore {
async fn get_refund_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 808f82b00a4..dbe7534ee28 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -80,7 +80,7 @@ pub trait RefundInterface {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>;
@@ -88,7 +88,7 @@ pub trait RefundInterface {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>;
@@ -817,7 +817,7 @@ mod storage {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -831,7 +831,7 @@ mod storage {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -1135,7 +1135,7 @@ impl RefundInterface for MockDb {
async fn filter_refund_by_meta_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
let refunds = self.refunds.lock().await;
@@ -1182,7 +1182,7 @@ impl RefundInterface for MockDb {
async fn get_refund_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> {
let refunds = self.refunds.lock().await;
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 5d8f7120f40..50a26ceae89 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -11,7 +11,7 @@ use super::app::AppState;
use crate::{
core::disputes,
services::{api, authentication as auth},
- types::api::{disputes as dispute_types, payments::TimeRange},
+ types::api::disputes as dispute_types,
};
/// Disputes - Retrieve Dispute
@@ -413,7 +413,7 @@ pub async fn delete_dispute_evidence(
pub async fn get_disputes_aggregate(
state: web::Data<AppState>,
req: HttpRequest,
- query_param: web::Query<TimeRange>,
+ query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
@@ -443,7 +443,7 @@ pub async fn get_disputes_aggregate(
pub async fn get_disputes_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
- query_param: web::Query<TimeRange>,
+ query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 82407976c6e..c8f4f5e4dd0 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -987,7 +987,7 @@ pub async fn profile_payments_list_by_filter(
pub async fn get_filters_for_payments(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Json<payment_types::TimeRange>,
+ payload: web::Json<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
@@ -1065,7 +1065,7 @@ pub async fn get_payment_filters_profile(
pub async fn get_payments_aggregates(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Query<payment_types::TimeRange>,
+ payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
@@ -1780,7 +1780,7 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest {
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Query<payment_types::TimeRange>,
+ payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 1b614330ebd..28b2afe2bee 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -8,8 +8,6 @@ use common_utils::consts;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
-#[cfg(feature = "olap")]
-use crate::types::api::payments as payment_types;
use crate::{
core::{api_locking, payouts::*},
headers::ACCEPT_LANGUAGE,
@@ -375,7 +373,7 @@ pub async fn payouts_list_by_filter_profile(
pub async fn payouts_list_available_filters_for_merchant(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<payment_types::TimeRange>,
+ json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
@@ -408,7 +406,7 @@ pub async fn payouts_list_available_filters_for_merchant(
pub async fn payouts_list_available_filters_for_profile(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<payment_types::TimeRange>,
+ json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index d21c351a927..40184c5fcfa 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -318,7 +318,7 @@ pub async fn refunds_list_profile(
pub async fn refunds_filter_list(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Json<api_models::payments::TimeRange>,
+ payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
@@ -426,7 +426,7 @@ pub async fn get_refunds_filters_profile(
pub async fn get_refunds_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
- query_params: web::Query<api_models::payments::TimeRange>,
+ query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 449d1c725c5..575725d4874 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -13,7 +13,7 @@ pub use api_models::payments::{
PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse,
PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse,
PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken,
- TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData,
+ UrlDetails, VerifyRequest, VerifyResponse, WalletData,
};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index 79b9a90343e..45f2073708b 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -19,7 +19,7 @@ pub trait DisputeDbExt: Sized {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
@@ -84,7 +84,7 @@ impl DisputeDbExt for Dispute {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 8e0040abfae..350c1032261 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -29,7 +29,7 @@ pub trait RefundDbExt: Sized {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::payments::TimeRange,
+ refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
async fn get_refunds_count(
@@ -41,7 +41,7 @@ pub trait RefundDbExt: Sized {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>;
}
@@ -158,7 +158,7 @@ impl RefundDbExt for Refund {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::payments::TimeRange,
+ refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
@@ -299,7 +299,7 @@ impl RefundDbExt for Refund {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::refund_status)
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 1a4595bdbbe..7abde140991 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -52,6 +52,7 @@ impl PaymentAttemptInterface for MockDb {
_payment_method_type: Option<Vec<PaymentMethodType>>,
_authentication_type: Option<Vec<AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ _time_range: Option<common_utils::types::TimeRange>,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 4cf8272650a..e0328871e33 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -41,7 +41,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
@@ -57,7 +57,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 5f2cc8824e5..c72a08a1823 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -86,7 +86,7 @@ impl PayoutsInterface for MockDb {
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index d1df6861657..9974393e100 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -403,6 +403,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -426,6 +427,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
+ time_range,
profile_id_list,
merchant_connector_id,
)
@@ -1289,6 +1291,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -1301,6 +1304,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
+ time_range,
profile_id_list,
storage_scheme,
)
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index cb58eac4b61..97fa5873cae 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -378,7 +378,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
@@ -402,7 +402,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
self.router_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
@@ -747,7 +747,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
@@ -773,7 +773,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index b6e1c1ac35f..2a49b01458f 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -368,7 +368,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
@@ -772,7 +772,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let payout_filters = (*time_range).into();
| 2024-09-19T11:00:46Z |
## Description
- Add time range to filter total count for payment attempt list.
- Move `TimeRange` type to common utils so that it can be used in diesel models and across all the other api models
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes #5958
## How did you test it?
The expected behaviour is same, the query that is getting printed, is now also considering time range.
```
SELECT COUNT(*) FROM "payment_attempt" WHERE ((("payment_attempt"."merchant_id" = $1)
AND ("payment_attempt"."attempt_id" = ANY($2))) AND ("payment_attempt"."created_at" >= $3))
-- binds: [MerchantId("merchant_1726040792"), [], 2024-08-19 18:30:00.0]
```
Request
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"start_time": "2024-08-19T18:30:00Z"
}'
```
Response:
```
{
"count": 0,
"total_count": 0,
"data": []
}
``` | 6a6ce17506932e0843140ef5b02ed201d0524d5d | The expected behaviour is same, the query that is getting printed, is now also considering time range.
```
SELECT COUNT(*) FROM "payment_attempt" WHERE ((("payment_attempt"."merchant_id" = $1)
AND ("payment_attempt"."attempt_id" = ANY($2))) AND ("payment_attempt"."created_at" >= $3))
-- binds: [MerchantId("merchant_1726040792"), [], 2024-08-19 18:30:00.0]
```
Request
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"start_time": "2024-08-19T18:30:00Z"
}'
```
Response:
```
{
"count": 0,
"total_count": 0,
"data": []
}
```
| [
"api-reference-v2/openapi_spec.json",
"crates/analytics/src/disputes/metrics.rs",
"crates/analytics/src/opensearch.rs",
"crates/api_models/src/analytics.rs",
"crates/api_models/src/analytics/search.rs",
"crates/api_models/src/events.rs",
"crates/api_models/src/payments.rs",
"crates/api_models/src/payo... | |
juspay/hyperswitch | juspay__hyperswitch-5956 | Bug: [BUG] using FRM with Signifyd throws 5xx
### Bug Description
Enabling Signifyd FRM connector for payments, and using this for a payment throws 5xx. This is due to Signifyd sending 303 which is not handled in HyperSwitch. Signifyd throws 303 as the URL is malformed.
https://api.signifyd.com//v3/orders/events/sales as opposed to https://api.signifyd.com/v3/orders/events/sales
### Expected Behavior
Calling any Signifyd API should return an expected status code.
### Actual Behavior
Calling any Signifyd API returns 303 - which is not handled in the response handler of `execute_connector_processing_step` leading to 500 - Something went wrong.
### Steps To Reproduce
1. Enable FRM via Signifyd for a payment connector
2. Create a payment
3. 5xx is thrown in API response
### 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/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs
index 6ba2dce9861..4ee36d8966b 100644
--- a/crates/router/src/connector/signifyd.rs
+++ b/crates/router/src/connector/signifyd.rs
@@ -237,7 +237,7 @@ impl
Ok(format!(
"{}{}",
self.base_url(connectors),
- "/v3/orders/events/sales"
+ "v3/orders/events/sales"
))
}
@@ -325,7 +325,7 @@ impl
Ok(format!(
"{}{}",
self.base_url(connectors),
- "/v3/orders/events/checkouts"
+ "v3/orders/events/checkouts"
))
}
@@ -413,7 +413,7 @@ impl
Ok(format!(
"{}{}",
self.base_url(connectors),
- "/v3/orders/events/transactions"
+ "v3/orders/events/transactions"
))
}
@@ -503,7 +503,7 @@ impl
Ok(format!(
"{}{}",
self.base_url(connectors),
- "/v3/orders/events/fulfillments"
+ "v3/orders/events/fulfillments"
))
}
@@ -593,7 +593,7 @@ impl
Ok(format!(
"{}{}",
self.base_url(connectors),
- "/v3/orders/events/returns/records"
+ "v3/orders/events/returns/records"
))
}
| 2024-09-19T09:26:00Z |
## Description
Described in #5956
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding 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 5xx thrown by payments API when FRM flows are consumed.
## How did you test it?
Locally - using an increased stack size. | 7076ae9244e26c08c61fdca328237963b3797a5a | Locally - using an increased stack size.
| [
"crates/router/src/connector/signifyd.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5969 | Bug: Add support for Samsung Pay payment method
This is to support for Samsung pay as a payment method.
This also needs to add a new field in merchant connector account create `connector_wallet_details` which is required to collect the required credentials for Samsung Pay. As this column in the data base stores the data in the encrypted format we also want to migrate apple pay certificates from metadata to `connector_wallet_details`, for which we are inserting apple pay details passed in the metadata to connector_wallet_details.
Once the frontend changes are done to pass the apple pay credentials in the connector_wallet_details this fallback can be removed. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 5465d902388..a250a8a9c37 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -5521,6 +5521,27 @@
}
}
},
+ "ConnectorWalletDetails": {
+ "type": "object",
+ "properties": {
+ "apple_pay_combined": {
+ "type": "object",
+ "description": "This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow",
+ "nullable": true
+ },
+ "apple_pay": {
+ "type": "object",
+ "description": "This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow",
+ "nullable": true
+ },
+ "samsung_pay": {
+ "type": "object",
+ "description": "This field contains the Samsung Pay certificates and credentials",
+ "nullable": true
+ }
+ },
+ "additionalProperties": false
+ },
"CountryAlpha2": {
"type": "string",
"enum": [
@@ -9254,6 +9275,14 @@
}
],
"nullable": true
+ },
+ "connector_wallets_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorWalletDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -9450,6 +9479,14 @@
}
],
"nullable": true
+ },
+ "connector_wallets_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorWalletDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -9591,6 +9628,14 @@
}
],
"nullable": true
+ },
+ "connector_wallets_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorWalletDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -9716,6 +9761,14 @@
}
],
"nullable": true
+ },
+ "connector_wallets_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorWalletDetails"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -17929,15 +17982,164 @@
}
}
},
- "SamsungPayWalletData": {
+ "SamsungPayAmountDetails": {
"type": "object",
"required": [
- "token"
+ "option",
+ "currency_code",
+ "total"
],
"properties": {
- "token": {
+ "option": {
+ "$ref": "#/components/schemas/SamsungPayAmountFormat"
+ },
+ "currency_code": {
+ "$ref": "#/components/schemas/Currency"
+ },
+ "total": {
+ "type": "string",
+ "description": "The total amount of the transaction",
+ "example": "38.02"
+ }
+ }
+ },
+ "SamsungPayAmountFormat": {
+ "type": "string",
+ "enum": [
+ "FORMAT_TOTAL_PRICE_ONLY",
+ "FORMAT_TOTAL_ESTIMATED_AMOUNT"
+ ]
+ },
+ "SamsungPayMerchantPaymentInformation": {
+ "type": "object",
+ "required": [
+ "name",
+ "url",
+ "country_code"
+ ],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Merchant name, this will be displayed on the Samsung Pay screen"
+ },
+ "url": {
+ "type": "string",
+ "description": "Merchant domain that process payments"
+ },
+ "country_code": {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ }
+ },
+ "SamsungPayProtocolType": {
+ "type": "string",
+ "enum": [
+ "PROTOCOL3DS"
+ ]
+ },
+ "SamsungPaySessionTokenResponse": {
+ "type": "object",
+ "required": [
+ "version",
+ "service_id",
+ "order_number",
+ "merchant",
+ "amount",
+ "protocol",
+ "allowed_brands"
+ ],
+ "properties": {
+ "version": {
+ "type": "string",
+ "description": "Samsung Pay API version"
+ },
+ "service_id": {
+ "type": "string",
+ "description": "Samsung Pay service ID to which session call needs to be made"
+ },
+ "order_number": {
+ "type": "string",
+ "description": "Order number of the transaction"
+ },
+ "merchant": {
+ "$ref": "#/components/schemas/SamsungPayMerchantPaymentInformation"
+ },
+ "amount": {
+ "$ref": "#/components/schemas/SamsungPayAmountDetails"
+ },
+ "protocol": {
+ "$ref": "#/components/schemas/SamsungPayProtocolType"
+ },
+ "allowed_brands": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "List of supported card brands"
+ }
+ }
+ },
+ "SamsungPayTokenData": {
+ "type": "object",
+ "required": [
+ "version",
+ "data"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "3DS type used by Samsung Pay",
+ "nullable": true
+ },
+ "version": {
"type": "string",
- "description": "The encrypted payment token from Samsung"
+ "description": "3DS version used by Samsung Pay"
+ },
+ "data": {
+ "type": "string",
+ "description": "Samsung Pay encrypted payment credential data"
+ }
+ }
+ },
+ "SamsungPayWalletCredentials": {
+ "type": "object",
+ "required": [
+ "card_brand",
+ "card_last4digits",
+ "3_d_s"
+ ],
+ "properties": {
+ "method": {
+ "type": "string",
+ "description": "Specifies authentication method used",
+ "nullable": true
+ },
+ "recurring_payment": {
+ "type": "boolean",
+ "description": "Value if credential is enabled for recurring payment",
+ "nullable": true
+ },
+ "card_brand": {
+ "type": "string",
+ "description": "Brand of the payment card"
+ },
+ "card_last4digits": {
+ "type": "string",
+ "description": "Last 4 digits of the card number"
+ },
+ "3_d_s": {
+ "$ref": "#/components/schemas/SamsungPayTokenData"
+ }
+ }
+ },
+ "SamsungPayWalletData": {
+ "type": "object",
+ "required": [
+ "payment_credential"
+ ],
+ "properties": {
+ "payment_credential": {
+ "$ref": "#/components/schemas/SamsungPayWalletCredentials"
}
}
},
@@ -18145,6 +18347,27 @@
}
]
},
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SamsungPaySessionTokenResponse"
+ },
+ {
+ "type": "object",
+ "required": [
+ "wallet_name"
+ ],
+ "properties": {
+ "wallet_name": {
+ "type": "string",
+ "enum": [
+ "samsung_pay"
+ ]
+ }
+ }
+ }
+ ]
+ },
{
"allOf": [
{
diff --git a/config/config.example.toml b/config/config.example.toml
index a6af984b01f..861785dc34c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -534,6 +534,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.stax]
credit = { currency = "USD" }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index abb50a2c2f0..3a54c5ef08f 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -304,6 +304,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.volt]
open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 38799c23858..ec3737a5c64 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -278,6 +278,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.braintree]
paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 2217a72429c..1c605ef35ac 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -281,6 +281,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.braintree]
paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD"
diff --git a/config/development.toml b/config/development.toml
index 43130cb78f2..6e56d5bb14d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -449,6 +449,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.braintree]
paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2c6b12a88a0..15038da0125 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -414,6 +414,7 @@ credit = { currency = "USD,GBP,EUR" }
debit = { currency = "USD,GBP,EUR" }
apple_pay = { currency = "USD,GBP,EUR" }
google_pay = { currency = "USD,GBP,EUR" }
+samsung_pay = { currency = "USD,GBP,EUR" }
[pm_filters.helcim]
credit = { currency = "USD" }
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 3b9a8e1c983..cbbb17525b6 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -736,6 +736,10 @@ pub struct MerchantConnectorCreate {
/// In case the merchant needs to store any additional sensitive data
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v2")]
@@ -873,6 +877,10 @@ pub struct MerchantConnectorCreate {
/// In case the merchant needs to store any additional sensitive data
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v1")]
@@ -1093,6 +1101,10 @@ pub struct MerchantConnectorResponse {
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v2")]
@@ -1212,6 +1224,10 @@ pub struct MerchantConnectorResponse {
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v1")]
@@ -1318,6 +1334,10 @@ pub struct MerchantConnectorListResponse {
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v1")]
@@ -1408,6 +1428,10 @@ pub struct MerchantConnectorListResponse {
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v2")]
@@ -1503,6 +1527,28 @@ pub struct MerchantConnectorUpdate {
/// In case the merchant needs to store any additional sensitive data
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ #[schema(value_type = Option<ConnectorWalletDetails>)]
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[serde(deny_unknown_fields)]
+
+pub struct ConnectorWalletDetails {
+ /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub apple_pay_combined: Option<pii::SecretSerdeValue>,
+ /// This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub apple_pay: Option<pii::SecretSerdeValue>,
+ /// This field contains the Samsung Pay certificates and credentials
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schema(value_type = Option<Object>)]
+ pub samsung_pay: Option<pii::SecretSerdeValue>,
}
/// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc."
@@ -1588,6 +1634,9 @@ pub struct MerchantConnectorUpdate {
/// In case the merchant needs to store any additional sensitive data
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
+
+ /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
+ pub connector_wallets_details: Option<ConnectorWalletDetails>,
}
#[cfg(feature = "v2")]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 715bf3c3544..59cc0e0548f 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2788,9 +2788,37 @@ impl GetAddressFromPaymentMethodData for WalletData {
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
- /// The encrypted payment token from Samsung
+ pub payment_credential: SamsungPayWalletCredentials,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct SamsungPayWalletCredentials {
+ /// Specifies authentication method used
+ pub method: Option<String>,
+ /// Value if credential is enabled for recurring payment
+ pub recurring_payment: Option<bool>,
+ /// Brand of the payment card
+ pub card_brand: String,
+ /// Last 4 digits of the card number
+ #[serde(rename = "card_last4digits")]
+ pub card_last_four_digits: String,
+ /// Samsung Pay token data
+ #[serde(rename = "3_d_s")]
+ pub token_data: SamsungPayTokenData,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct SamsungPayTokenData {
+ /// 3DS type used by Samsung Pay
+ #[serde(rename = "type")]
+ pub three_ds_type: Option<String>,
+ /// 3DS version used by Samsung Pay
+ pub version: String,
+ /// Samsung Pay encrypted payment credential data
#[schema(value_type = String)]
- pub token: Secret<String>,
+ pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
@@ -4789,6 +4817,20 @@ pub struct GpaySessionTokenData {
pub data: GpayMetaData,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SamsungPaySessionTokenData {
+ #[serde(rename = "samsung_pay")]
+ pub data: SamsungPayMetadata,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SamsungPayMetadata {
+ pub service_id: String,
+ pub merchant_display_name: String,
+ pub merchant_business_country: api_enums::CountryAlpha2,
+ pub allowed_brands: Vec<String>,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaypalSdkMetaData {
pub client_id: String,
@@ -4954,6 +4996,8 @@ pub struct SessionTokenForSimplifiedApplePay {
pub enum SessionToken {
/// The session response structure for Google Pay
GooglePay(Box<GpaySessionTokenResponse>),
+ /// The session response structure for Samsung Pay
+ SamsungPay(Box<SamsungPaySessionTokenResponse>),
/// The session response structure for Klarna
Klarna(Box<KlarnaSessionTokenResponse>),
/// The session response structure for PayPal
@@ -5011,6 +5055,68 @@ pub struct GooglePaySessionResponse {
pub secrets: Option<SecretInfoToInitiateSdk>,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct SamsungPaySessionTokenResponse {
+ /// Samsung Pay API version
+ pub version: String,
+ /// Samsung Pay service ID to which session call needs to be made
+ pub service_id: String,
+ /// Order number of the transaction
+ pub order_number: String,
+ /// Field containing merchant information
+ #[serde(rename = "merchant")]
+ pub merchant_payment_information: SamsungPayMerchantPaymentInformation,
+ /// Field containing the payment amount
+ pub amount: SamsungPayAmountDetails,
+ /// Payment protocol type
+ pub protocol: SamsungPayProtocolType,
+ /// List of supported card brands
+ pub allowed_brands: Vec<String>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum SamsungPayProtocolType {
+ Protocol3ds,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct SamsungPayMerchantPaymentInformation {
+ /// Merchant name, this will be displayed on the Samsung Pay screen
+ pub name: String,
+ /// Merchant domain that process payments
+ pub url: String,
+ /// Merchant country code
+ #[schema(value_type = CountryAlpha2, example = "US")]
+ pub country_code: api_enums::CountryAlpha2,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct SamsungPayAmountDetails {
+ #[serde(rename = "option")]
+ /// Amount format to be displayed
+ pub amount_format: SamsungPayAmountFormat,
+ /// The currency code
+ #[schema(value_type = Currency, example = "USD")]
+ pub currency_code: api_enums::Currency,
+ /// The total amount of the transaction
+ #[serde(rename = "total")]
+ #[schema(value_type = String, example = "38.02")]
+ pub total_amount: StringMajorUnit,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum SamsungPayAmountFormat {
+ /// Display the total amount only
+ FormatTotalPriceOnly,
+ /// Display "Total (Estimated amount)" and total amount
+ FormatTotalEstimatedAmount,
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub struct GpayShippingAddressParameters {
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index fe39da67a93..68ade2909b4 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -56,7 +56,7 @@ impl DashboardRequestPayload {
| (Connector::Stripe, WeChatPay) => {
Some(api_models::enums::PaymentExperience::DisplayQrCode)
}
- (_, GooglePay) | (_, ApplePay) => {
+ (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
_ => Some(api_models::enums::PaymentExperience::RedirectToUrl),
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index b21bedd880c..9f505f26712 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -135,10 +135,30 @@ pub struct MifinityData {
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
-
+#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
- /// The encrypted payment token from Samsung
- pub token: Secret<String>,
+ pub payment_credential: SamsungPayWalletCredentials,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SamsungPayWalletCredentials {
+ pub method: Option<String>,
+ pub recurring_payment: Option<bool>,
+ pub card_brand: String,
+ #[serde(rename = "card_last4digits")]
+ pub card_last_four_digits: String,
+ #[serde(rename = "3_d_s")]
+ pub token_data: SamsungPayTokenData,
+}
+
+#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SamsungPayTokenData {
+ #[serde(rename = "type")]
+ pub three_ds_type: Option<String>,
+ pub version: String,
+ pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
@@ -670,9 +690,7 @@ impl From<api_models::payments::WalletData> for WalletData {
})
}
api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
- Self::SamsungPay(Box::new(SamsungPayWalletData {
- token: samsung_pay_data.token,
- }))
+ Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data)))
}
api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
@@ -736,6 +754,24 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
}
}
+impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData {
+ fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self {
+ Self {
+ payment_credential: SamsungPayWalletCredentials {
+ method: value.payment_credential.method,
+ recurring_payment: value.payment_credential.recurring_payment,
+ card_brand: value.payment_credential.card_brand,
+ card_last_four_digits: value.payment_credential.card_last_four_digits,
+ token_data: SamsungPayTokenData {
+ three_ds_type: value.payment_credential.token_data.three_ds_type,
+ version: value.payment_credential.token_data.version,
+ data: value.payment_credential.token_data.data,
+ },
+ },
+ }
+ }
+}
+
impl From<api_models::payments::PayLaterData> for PayLaterData {
fn from(value: api_models::payments::PayLaterData) -> Self {
match value {
diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs
index e36707af6b0..f9c407ff587 100644
--- a/crates/hyperswitch_interfaces/src/errors.rs
+++ b/crates/hyperswitch_interfaces/src/errors.rs
@@ -41,6 +41,8 @@ pub enum ConnectorError {
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
+ #[error("Connector wallet details not found")]
+ NoConnectorWalletDetails,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs
index b98b854fba8..858c013f41d 100644
--- a/crates/kgraph_utils/benches/evaluation.rs
+++ b/crates/kgraph_utils/benches/evaluation.rs
@@ -71,6 +71,7 @@ fn build_test_data(
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
+ connector_wallets_details: None,
};
#[cfg(feature = "v1")]
@@ -95,6 +96,7 @@ fn build_test_data(
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
+ connector_wallets_details: None,
};
let config = CountryCurrencyFilter {
connector_configs: HashMap::new(),
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index 7d04f5d4238..2ec0cbe8031 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -759,6 +759,7 @@ mod tests {
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
+ connector_wallets_details: None,
};
#[cfg(feature = "v1")]
let stripe_account = MerchantConnectorResponse {
@@ -818,6 +819,7 @@ mod tests {
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
additional_merchant_data: None,
+ connector_wallets_details: None,
};
let config_map = kgraph_types::CountryCurrencyFilter {
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b626b7d4418..3d56a42222f 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -271,6 +271,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::UIWidgetFormLayout,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
+ api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
@@ -408,6 +409,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GpayTokenizationData,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
+ api_models::payments::SamsungPayWalletCredentials,
+ api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
@@ -429,6 +432,11 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
+ api_models::payments::SamsungPaySessionTokenResponse,
+ api_models::payments::SamsungPayMerchantPaymentInformation,
+ api_models::payments::SamsungPayAmountDetails,
+ api_models::payments::SamsungPayAmountFormat,
+ api_models::payments::SamsungPayProtocolType,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index f12d6a7b567..0dbf5f9cdcf 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -197,6 +197,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::enums::UIWidgetFormLayout,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
+ api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
@@ -335,6 +336,13 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
+ api_models::payments::SamsungPaySessionTokenResponse,
+ api_models::payments::SamsungPayMerchantPaymentInformation,
+ api_models::payments::SamsungPayAmountDetails,
+ api_models::payments::SamsungPayAmountFormat,
+ api_models::payments::SamsungPayProtocolType,
+ api_models::payments::SamsungPayWalletCredentials,
+ api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index e915d05c358..1d49a99106e 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2083,7 +2083,7 @@ impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)>
domain::WalletData::SamsungPay(samsung_data) => {
let data = SamsungPayPmData {
payment_type: PaymentType::Samsungpay,
- samsung_pay_token: samsung_data.token.to_owned(),
+ samsung_pay_token: samsung_data.payment_credential.token_data.data.to_owned(),
};
Ok(AdyenPaymentMethod::SamsungPay(Box::new(data)))
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index fc35cab773a..e83e5c33052 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -436,12 +436,27 @@ pub struct FluidData {
pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U";
+pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT";
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentInformation {
fluid_data: FluidData,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SamsungPayTokenizedCard {
+ transaction_type: TransactionType,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SamsungPayPaymentInformation {
+ fluid_data: FluidData,
+ tokenized_card: SamsungPayTokenizedCard,
+}
+
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaymentInformation {
@@ -450,6 +465,7 @@ pub enum PaymentInformation {
ApplePay(Box<ApplePayPaymentInformation>),
ApplePayToken(Box<ApplePayTokenPaymentInformation>),
MandatePayment(Box<MandatePaymentInformation>),
+ SamsungPay(Box<SamsungPayPaymentInformation>),
NetworkToken(Box<NetworkTokenPaymentInformation>),
}
@@ -504,12 +520,15 @@ pub struct AdditionalAmount {
pub enum PaymentSolution {
ApplePay,
GooglePay,
+ SamsungPay,
}
#[derive(Debug, Serialize)]
pub enum TransactionType {
#[serde(rename = "1")]
ApplePay,
+ #[serde(rename = "1")]
+ SamsungPay,
}
impl From<PaymentSolution> for String {
@@ -517,6 +536,7 @@ impl From<PaymentSolution> for String {
let payment_solution = match solution {
PaymentSolution::ApplePay => "001",
PaymentSolution::GooglePay => "012",
+ PaymentSolution::SamsungPay => "008",
};
payment_solution.to_string()
}
@@ -575,7 +595,7 @@ impl
let mut commerce_indicator = solution
.as_ref()
.map(|pm_solution| match pm_solution {
- PaymentSolution::ApplePay => network
+ PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"amex" => "aesk",
@@ -1491,6 +1511,66 @@ impl
}
}
+impl
+ TryFrom<(
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Box<domain::SamsungPayWalletData>,
+ )> for CybersourcePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, samsung_pay_data): (
+ &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ Box<domain::SamsungPayWalletData>,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let email = item
+ .router_data
+ .get_billing_email()
+ .or(item.router_data.request.get_email())?;
+ let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?;
+ let order_information = OrderInformationWithBill::from((item, Some(bill_to)));
+
+ let payment_information =
+ PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation {
+ fluid_data: FluidData {
+ value: Secret::from(
+ consts::BASE64_ENGINE
+ .encode(samsung_pay_data.payment_credential.token_data.data.peek()),
+ ),
+ descriptor: Some(
+ consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY),
+ ),
+ },
+ tokenized_card: SamsungPayTokenizedCard {
+ transaction_type: TransactionType::SamsungPay,
+ },
+ }));
+
+ let processing_information = ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::SamsungPay),
+ Some(samsung_pay_data.payment_credential.card_brand),
+ ))?;
+ let client_reference_information = ClientReferenceInformation::from(item);
+ let merchant_defined_information = item
+ .router_data
+ .request
+ .metadata
+ .clone()
+ .map(Vec::<MerchantDefinedInformation>::foreign_from);
+
+ Ok(Self {
+ processing_information,
+ payment_information,
+ order_information,
+ client_reference_information,
+ consumer_authentication_information: None,
+ merchant_defined_information,
+ })
+ }
+}
+
impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
for CybersourcePaymentsRequest
{
@@ -1588,6 +1668,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
domain::WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
+ domain::WalletData::SamsungPay(samsung_pay_data) => {
+ Self::try_from((item, samsung_pay_data))
+ }
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
@@ -1604,7 +1687,6 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
| domain::WalletData::MobilePayRedirect(_)
| domain::WalletData::PaypalRedirect(_)
| domain::WalletData::PaypalSdk(_)
- | domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
| domain::WalletData::TouchNGoRedirect(_)
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 95b02f0cdb3..19b44a2bf8e 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2125,10 +2125,14 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
} else {
None
},
- connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
- state, &key_store, &metadata,
- )
- .await?,
+ connector_wallets_details:
+ helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(
+ state,
+ &key_store,
+ &metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
})
}
}
@@ -2302,10 +2306,14 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
} else {
None
},
- connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
- state, &key_store, &metadata,
- )
- .await?,
+ connector_wallets_details:
+ helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(
+ state,
+ &key_store,
+ &metadata,
+ &self.connector_wallets_details,
+ )
+ .await?,
})
}
}
@@ -2436,7 +2444,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
- connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(state, &key_store, &self.metadata).await?,
+ connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?,
additional_merchant_data: if let Some(mcd) = merchant_recipient_data {
Some(domain_types::crypto_operation(
key_manager_state,
@@ -2601,7 +2609,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
- connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(state, &key_store, &self.metadata).await?,
+ connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?,
test_mode: self.test_mode,
business_country: self.business_country,
business_label: self.business_label.clone(),
diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs
index 0dca02bf79d..88e1eb80618 100644
--- a/crates/router/src/core/connector_onboarding/paypal.rs
+++ b/crates/router/src/core/connector_onboarding/paypal.rs
@@ -162,6 +162,7 @@ pub async fn update_mca(
pm_auth_config: None,
test_mode: None,
additional_merchant_data: None,
+ connector_wallets_details: None,
};
#[cfg(feature = "v2")]
let request = MerchantConnectorUpdate {
@@ -177,6 +178,7 @@ pub async fn update_mca(
pm_auth_config: None,
merchant_id: merchant_id.clone(),
additional_merchant_data: None,
+ connector_wallets_details: None,
};
let mca_response =
admin::update_connector(state.clone(), &merchant_id, None, &connector_id, request).await?;
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index d2812447ed8..847aef2ba3b 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -185,6 +185,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
| errors::ConnectorError::FailedToObtainAuthType
| errors::ConnectorError::FailedToObtainCertificate
| errors::ConnectorError::NoConnectorMetaData
+ | errors::ConnectorError::NoConnectorWalletDetails
| errors::ConnectorError::FailedToObtainCertificateKey
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::CaptureMethodNotSupported
@@ -284,7 +285,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
errors::ConnectorError::InvalidWallet |
errors::ConnectorError::ResponseHandlingFailed |
errors::ConnectorError::FailedToObtainCertificate |
- errors::ConnectorError::NoConnectorMetaData |
+ errors::ConnectorError::NoConnectorMetaData | errors::ConnectorError::NoConnectorWalletDetails |
errors::ConnectorError::FailedToObtainCertificateKey |
errors::ConnectorError::CaptureMethodNotSupported |
errors::ConnectorError::MissingConnectorMandateID |
@@ -370,6 +371,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
| errors::ConnectorError::FailedToObtainAuthType
| errors::ConnectorError::FailedToObtainCertificate
| errors::ConnectorError::NoConnectorMetaData
+ | errors::ConnectorError::NoConnectorWalletDetails
| errors::ConnectorError::FailedToObtainCertificateKey
| errors::ConnectorError::NotImplemented(_)
| errors::ConnectorError::NotSupported { .. }
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 54d8dc230c7..6159776a551 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -496,6 +496,62 @@ async fn create_applepay_session_token(
}
}
+fn create_samsung_pay_session_token(
+ router_data: &types::PaymentsSessionRouterData,
+ header_payload: api_models::payments::HeaderPayload,
+) -> RouterResult<types::PaymentsSessionRouterData> {
+ let samsung_pay_wallet_details = router_data
+ .connector_wallets_details
+ .clone()
+ .parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
+ .change_context(errors::ConnectorError::NoConnectorWalletDetails)
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "connector_wallets_details".to_string(),
+ expected_format: "samsung_pay_metadata_format".to_string(),
+ })?;
+
+ let required_amount_type = StringMajorUnitForConnector;
+ let samsung_pay_amount = required_amount_type
+ .convert(
+ router_data.request.minor_amount,
+ router_data.request.currency,
+ )
+ .change_context(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Failed to convert amount to string major unit for Samsung Pay".to_string(),
+ })?;
+
+ let merchant_domain = header_payload
+ .x_merchant_domain
+ .get_required_value("samsung pay domain")
+ .attach_printable("Failed to get domain for samsung pay session call")?;
+
+ Ok(types::PaymentsSessionRouterData {
+ response: Ok(types::PaymentsResponseData::SessionResponse {
+ session_token: payment_types::SessionToken::SamsungPay(Box::new(
+ payment_types::SamsungPaySessionTokenResponse {
+ version: "2".to_string(),
+ service_id: samsung_pay_wallet_details.data.service_id,
+ order_number: router_data.payment_id.clone(),
+ merchant_payment_information:
+ payment_types::SamsungPayMerchantPaymentInformation {
+ name: samsung_pay_wallet_details.data.merchant_display_name,
+ url: merchant_domain,
+ country_code: samsung_pay_wallet_details.data.merchant_business_country,
+ },
+ amount: payment_types::SamsungPayAmountDetails {
+ amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
+ currency_code: router_data.request.currency,
+ total_amount: samsung_pay_amount,
+ },
+ protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
+ allowed_brands: samsung_pay_wallet_details.data.allowed_brands,
+ },
+ )),
+ }),
+ ..router_data.clone()
+ })
+}
+
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
@@ -881,6 +937,9 @@ impl RouterDataSession for types::PaymentsSessionRouterData {
api::GetToken::GpayMetadata => {
create_gpay_session_token(state, self, connector, business_profile)
}
+ api::GetToken::SamsungPayMetadata => {
+ create_samsung_pay_session_token(self, header_payload)
+ }
api::GetToken::ApplePayMetadata => {
create_applepay_session_token(
state,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 81d9130db85..7447323d9f0 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4467,30 +4467,34 @@ pub fn is_apple_pay_simplified_flow(
))
}
-pub async fn get_encrypted_apple_pay_connector_wallets_details(
+// This function will return the encrypted connector wallets details with Apple Pay certificates
+// Currently apple pay certifiactes are stored in the metadata which is not encrypted.
+// In future we want those certificates to be encrypted and stored in the connector_wallets_details.
+// As part of migration fallback this function checks apple pay details are present in connector_wallets_details
+// If yes, it will encrypt connector_wallets_details and store it in the database.
+// If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it.
+pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
connector_metadata: &Option<masking::Secret<tera::Value>>,
+ connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> {
- let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone())
- .map_err(|error| {
- logger::error!(
- "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}",
- error
- )
- })
- .ok();
+ let connector_wallet_details_with_apple_pay_metadata_optional =
+ get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
+ .await?;
- let connector_apple_pay_details = apple_pay_metadata
- .map(|metadata| {
- serde_json::to_value(metadata)
+ let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
+ .map(|details| {
+ serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to serialize apple pay metadata as JSON")
+ .attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
+
let key_manager_state: KeyManagerState = state.into();
- let encrypted_connector_apple_pay_details = connector_apple_pay_details
+ let encrypted_connector_wallets_details = connector_wallets_details
+ .clone()
.async_lift(|wallets_details| async {
types::crypto_operation(
&key_manager_state,
@@ -4505,7 +4509,86 @@ pub async fn get_encrypted_apple_pay_connector_wallets_details(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting connector wallets details")?;
- Ok(encrypted_connector_apple_pay_details)
+
+ Ok(encrypted_connector_wallets_details)
+}
+
+async fn get_apple_pay_metadata_if_needed(
+ connector_metadata: &Option<masking::Secret<tera::Value>>,
+ connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
+) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
+ if let Some(connector_wallets_details) = connector_wallets_details_optional {
+ if connector_wallets_details.apple_pay_combined.is_some()
+ || connector_wallets_details.apple_pay.is_some()
+ {
+ return Ok(Some(connector_wallets_details.clone()));
+ }
+ // Otherwise, merge Apple Pay metadata
+ return get_and_merge_apple_pay_metadata(
+ connector_metadata.clone(),
+ Some(connector_wallets_details.clone()),
+ )
+ .await;
+ }
+
+ // If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
+ get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
+}
+
+async fn get_and_merge_apple_pay_metadata(
+ connector_metadata: Option<masking::Secret<tera::Value>>,
+ connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
+) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
+ let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
+ .map_err(|error| {
+ logger::error!(
+ "Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
+ error
+ );
+ })
+ .ok();
+
+ if let Some(apple_pay_metadata) = apple_pay_metadata_optional {
+ let updated_wallet_details = match apple_pay_metadata {
+ api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
+ apple_pay_combined_metadata,
+ ) => {
+ let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?;
+
+ api_models::admin::ConnectorWalletDetails {
+ apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)),
+ apple_pay: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.apple_pay.clone()),
+ samsung_pay: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.samsung_pay.clone()),
+ }
+ }
+ api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
+ let metadata_json = serde_json::to_value(apple_pay_metadata)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize Apple Pay metadata as JSON")?;
+
+ api_models::admin::ConnectorWalletDetails {
+ apple_pay: Some(masking::Secret::new(metadata_json)),
+ apple_pay_combined: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.apple_pay_combined.clone()),
+ samsung_pay: connector_wallets_details_optional
+ .as_ref()
+ .and_then(|d| d.samsung_pay.clone()),
+ }
+ }
+ };
+
+ return Ok(Some(updated_wallet_details));
+ }
+
+ // Return connector_wallets_details if no Apple Pay metadata was found
+ Ok(connector_wallets_details_optional)
}
pub fn get_applepay_metadata(
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index f12cd71cdb0..1807369a029 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -490,6 +490,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken {
match value {
api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata,
api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata,
+ api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata,
api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata,
_ => Self::Connector,
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 34dea537b2d..dd5e47b1005 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -190,6 +190,7 @@ pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>;
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum GetToken {
GpayMetadata,
+ SamsungPayMetadata,
ApplePayMetadata,
PaypalSdkMetadata,
Connector,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a6f6d7c4c5a..a503f24d94c 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1068,6 +1068,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
+ connector_wallets_details: item
+ .connector_wallets_details
+ .map(|data| {
+ data.into_inner()
+ .expose()
+ .parse_value::<api_models::admin::ConnectorWalletDetails>(
+ "ConnectorWalletDetails",
+ )
+ .attach_printable("Unable to deserialize connector_wallets_details")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ })
+ .transpose()?,
};
#[cfg(feature = "v2")]
let response = Self {
@@ -1096,6 +1108,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
+ connector_wallets_details: item
+ .connector_wallets_details
+ .map(|data| {
+ data.into_inner()
+ .expose()
+ .parse_value::<api_models::admin::ConnectorWalletDetails>(
+ "ConnectorWalletDetails",
+ )
+ .attach_printable("Unable to deserialize connector_wallets_details")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ })
+ .transpose()?,
};
Ok(response)
}
@@ -1191,6 +1215,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
+ connector_wallets_details: item
+ .connector_wallets_details
+ .map(|data| {
+ data.into_inner()
+ .expose()
+ .parse_value::<api_models::admin::ConnectorWalletDetails>(
+ "ConnectorWalletDetails",
+ )
+ .attach_printable("Unable to deserialize connector_wallets_details")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ })
+ .transpose()?,
};
#[cfg(feature = "v1")]
let response = Self {
@@ -1235,6 +1271,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
})
.transpose()?
.map(api_models::admin::AdditionalMerchantData::foreign_from),
+ connector_wallets_details: item
+ .connector_wallets_details
+ .map(|data| {
+ data.into_inner()
+ .expose()
+ .parse_value::<api_models::admin::ConnectorWalletDetails>(
+ "ConnectorWalletDetails",
+ )
+ .attach_printable("Unable to deserialize connector_wallets_details")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ })
+ .transpose()?,
};
Ok(response)
}
| 2024-09-19T08:10:50Z |
## Description
<!-- Describe your changes in detail -->
This pr is to support for Samsung pay as a payment method.
This pr also adds a new field in merchant connector account create `connector_wallet_details` which is required to collect the required credentials for Samsung Pay. As this column in the data base stores the data in the encrypted format we also want to migrate apple pay certificates from metadata to `connector_wallet_details`, for which we are inserting apple pay details passed in the metadata to connector_wallet_details.
Once the frontend changes are done to pass the apple pay credentials in the connector_wallet_details this fallback can be removed.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
Test Samsung Pay flow
-> Enable Samsung Pay payment method for the connector
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data '{
"amount": 100000,
"currency": "INR",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726743607"
}'
```
```
{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"merchant_id": "merchant_1726725490",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi",
"created": "2024-09-19T11:00:15.562Z",
"currency": "INR",
"customer_id": "cu_1726743615",
"customer": {
"id": "cu_1726743615",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726743615",
"created_at": 1726743615,
"expires": 1726747215,
"secret": "epk_3d5ad79c88554ee7bf0748ae18ecd05b"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XdGC3A6KTKR5n2WDLON5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T11:15:15.562Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T11:00:15.680Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Safari' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_c23e25c5054241288a778316e463e309' \
--data '{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"wallets": [],
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi"
}'
```
```
{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi",
"session_token": [
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_on1wv5l8OM8A3VuDe2GN",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "INR",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
]
}
```
-> Confirm call
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "1234",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": "encrypted samsung pay data"
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_0lHEl7IAq7cFn680x4HJ",
"merchant_id": "merchant_1726725490",
"status": "failed",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_0lHEl7IAq7cFn680x4HJ_secret_3bsNpl8N5rArpWizVWik",
"created": "2024-09-19T11:28:58.596Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": "INVALID_DATA",
"error_message": "Declined - One or more fields in the request contains invalid data, detailed_error_information: paymentInformation.fluidData.value : INVALID_DATA",
"unified_code": "UE_000",
"unified_message": "Something went wrong",
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1726745338,
"expires": 1726748938,
"secret": "epk_48f2e9de3ad641578f3df9e9a46d9c80"
},
"manual_retry_allowed": true,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XdGC3A6KTKR5n2WDLON5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_TO5NdOnj3ohWTfxBKGsc",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T11:43:58.596Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T11:29:00.222Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
The status will be failed as Samsung does not have a test card and cybersource returns invalid data error for live cards | 5942e059e9efa3fa71a13cacc896509515e2f976 |
Test Samsung Pay flow
-> Enable Samsung Pay payment method for the connector
```
{
"connector_type": "payment_processor",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_secret": "api_secret",
"key1": "key1",
"api_key": "api_key"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"Discover",
"DinersClub"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "samsung_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_wallets_details": {
"samsung_pay": {
"service_id": "49400558c67f4a97b3925f",
"merchant_display_name": "Hyperswitch",
"merchant_business_country": "IN",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
},
"connector_webhook_details": {
"merchant_secret": "merchant_secret"
}
}
```
-> Create a payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data '{
"amount": 100000,
"currency": "INR",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1726743607"
}'
```
```
{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"merchant_id": "merchant_1726725490",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi",
"created": "2024-09-19T11:00:15.562Z",
"currency": "INR",
"customer_id": "cu_1726743615",
"customer": {
"id": "cu_1726743615",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cu_1726743615",
"created_at": 1726743615,
"expires": 1726747215,
"secret": "epk_3d5ad79c88554ee7bf0748ae18ecd05b"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XdGC3A6KTKR5n2WDLON5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T11:15:15.562Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T11:00:15.680Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
-> Session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Safari' \
--header 'x-merchant-domain: sdk-test-app.netlify.app' \
--header 'api-key: pk_dev_c23e25c5054241288a778316e463e309' \
--data '{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"wallets": [],
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi"
}'
```
```
{
"payment_id": "pay_on1wv5l8OM8A3VuDe2GN",
"client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi",
"session_token": [
{
"wallet_name": "samsung_pay",
"version": "2",
"service_id": "49400558c67f4a97b3925f",
"order_number": "pay_on1wv5l8OM8A3VuDe2GN",
"merchant": {
"name": "Hyperswitch",
"url": "sdk-test-app.netlify.app",
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "INR",
"total": "1000.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
}
]
}
```
-> Confirm call
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \
--data-raw '{
"amount": 1,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 1,
"customer_id": "custhype123",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "samsung_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"samsung_pay": {
"payment_credential": {
"card_brand": "visa",
"recurring_payment": false,
"card_last4digits": "1234",
"method": "3DS",
"3_d_s": {
"type": "S",
"version": "100",
"data": "encrypted samsung pay data"
}
}
}
}
}
}'
```
```
{
"payment_id": "pay_0lHEl7IAq7cFn680x4HJ",
"merchant_id": "merchant_1726725490",
"status": "failed",
"amount": 1,
"net_amount": 1,
"amount_capturable": 0,
"amount_received": null,
"connector": "cybersource",
"client_secret": "pay_0lHEl7IAq7cFn680x4HJ_secret_3bsNpl8N5rArpWizVWik",
"created": "2024-09-19T11:28:58.596Z",
"currency": "USD",
"customer_id": "custhype123",
"customer": {
"id": "custhype123",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": null,
"cancellation_reason": null,
"error_code": "INVALID_DATA",
"error_message": "Declined - One or more fields in the request contains invalid data, detailed_error_information: paymentInformation.fluidData.value : INVALID_DATA",
"unified_code": "UE_000",
"unified_message": "Something went wrong",
"payment_experience": null,
"payment_method_type": "samsung_pay",
"connector_label": "cybersource_US_default_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "custhype123",
"created_at": 1726745338,
"expires": 1726748938,
"secret": "epk_48f2e9de3ad641578f3df9e9a46d9c80"
},
"manual_retry_allowed": true,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_XdGC3A6KTKR5n2WDLON5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_TO5NdOnj3ohWTfxBKGsc",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-19T11:43:58.596Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-19T11:29:00.222Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
The status will be failed as Samsung does not have a test card and cybersource returns invalid data error for live cards
| [
"api-reference-v2/openapi_spec.json",
"config/config.example.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/api_models/src/admin.rs",
"crates/api_models/src/p... | |
juspay/hyperswitch | juspay__hyperswitch-5952 | Bug: [CHORE]: update docker compose toml
### Feature Description
remove the network_tokenization_service config
### Possible Implementation
remove the network_tokenization_service config
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 698800f082d..f0d44db4d5e 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -597,15 +597,5 @@ recon = "recon@example.com"
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
-[network_tokenization_service]
-generate_token_url= ""
-fetch_token_url= ""
-token_service_api_key= ""
-public_key= ""
-private_key= ""
-key_id= ""
-delete_token_url= ""
-check_token_status_url= ""
-
[network_tokenization_supported_connectors]
connector_list = "cybersource"
| 2024-09-19T06:58:00Z |
## Description
<!-- Describe your changes in detail -->
remove the network_tokenization_service from the config

### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Test is not required | 769111c20b0f745a5e4fc3ed6c9a705f277c3d5b |
Test is not required
| [
"config/docker_compose.toml"
] | |
juspay/hyperswitch | juspay__hyperswitch-5946 | Bug: fix(external_services): add proto compilation under a feature flag
add proto compilation under a feature flag | diff --git a/config/config.example.toml b/config/config.example.toml
index a6af984b01f..8345185238d 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -748,3 +748,7 @@ check_token_status_url= "" # base url to check token status from token servic
[network_tokenization_supported_connectors]
connector_list = "cybersource" # Supported connectors for network tokenization
+
+[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
+host = "localhost" # Client Host
+port = 7000 # Client Port
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 62350376271..319cdafed1d 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -311,3 +311,7 @@ private_key= "" # private key to decrypt response payload from to
key_id= "" # key id to encrypt data for token service
delete_token_url= "" # base url to delete token from token service
check_token_status_url= "" # base url to check token status from token service
+
+[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
+host = "localhost" # Client Host
+port = 7000 # Client Port
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index a882cdc9f51..fd7391c13bc 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -13,7 +13,7 @@ email = ["dep:aws-config"]
aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]
hashicorp-vault = ["dep:vaultrs"]
v1 = ["hyperswitch_interfaces/v1"]
-dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread"]
+dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread" , "dep:tonic-build", "dep:router_env"]
[dependencies]
async-trait = "0.1.79"
@@ -49,7 +49,8 @@ api_models = { version = "0.1.0", path = "../api_models", optional = true }
[build-dependencies]
-tonic-build = "0.12"
+tonic-build = { version = "0.12" , optional = true }
+router_env = { version = "0.1.0", path = "../router_env", default-features = false, optional = true }
[lints]
workspace = true
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
index 61e19f308d8..605ef699715 100644
--- a/crates/external_services/build.rs
+++ b/crates/external_services/build.rs
@@ -1,15 +1,13 @@
-use std::{env, path::PathBuf};
-
#[allow(clippy::expect_used)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
- // Get the directory of the current crate
- let crate_dir = env::var("CARGO_MANIFEST_DIR")?;
- let proto_file = PathBuf::from(crate_dir)
- .join("..")
- .join("..")
- .join("proto")
- .join("success_rate.proto");
- // Compile the .proto file
- tonic_build::compile_protos(proto_file).expect("Failed to compile protos ");
+ #[cfg(feature = "dynamic_routing")]
+ {
+ // Get the directory of the current crate
+ let proto_file = router_env::workspace_path()
+ .join("proto")
+ .join("success_rate.proto");
+ // Compile the .proto file
+ tonic_build::compile_protos(proto_file).expect("Failed to compile success rate proto file");
+ }
Ok(())
}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index 17bd43ca3a8..2681bffb0ce 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -112,12 +112,12 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
let params = success_rate_based_config
.params
.map(|vec| {
- vec.into_iter().fold(String::new(), |mut acc_vec, params| {
- if !acc_vec.is_empty() {
- acc_vec.push(':')
+ vec.into_iter().fold(String::new(), |mut acc_str, params| {
+ if !acc_str.is_empty() {
+ acc_str.push(':')
}
- acc_vec.push_str(params.to_string().as_str());
- acc_vec
+ acc_str.push_str(params.to_string().as_str());
+ acc_str
})
})
.get_required_value("params")
@@ -177,12 +177,12 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
let params = success_rate_based_config
.params
.map(|vec| {
- vec.into_iter().fold(String::new(), |mut acc_vec, params| {
- if !acc_vec.is_empty() {
- acc_vec.push(':')
+ vec.into_iter().fold(String::new(), |mut acc_str, params| {
+ if !acc_str.is_empty() {
+ acc_str.push(':')
}
- acc_vec.push_str(params.to_string().as_str());
- acc_vec
+ acc_str.push_str(params.to_string().as_str());
+ acc_str
})
})
.get_required_value("params")
| 2024-09-18T10:38:19Z |
## Description
add proto build under the dynamic_routing feature flag. Now the application would run without having to install protoc
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
Cannot be tested as it is for compiling the application without having to mandatorily install proton | c8f7232a3001be1fc5d8b0fedfd703030df83789 | Cannot be tested as it is for compiling the application without having to mandatorily install proton
| [
"config/config.example.toml",
"config/deployments/env_specific.toml",
"crates/external_services/Cargo.toml",
"crates/external_services/build.rs",
"crates/external_services/src/grpc_client/dynamic_routing.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5941 | Bug: Update and Retrieve PM APIs
### Feature Description
- Update Payment methods API
- Retrieve Payment Method API | diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 6c93b0bb5bd..1a82dc0e26b 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -374,7 +374,7 @@ pub struct PaymentMethodUpdate {
#[serde(deny_unknown_fields)]
pub struct PaymentMethodUpdate {
/// payment method data to be passed
- pub payment_method_data: Option<PaymentMethodUpdateData>,
+ pub payment_method_data: PaymentMethodUpdateData,
/// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
#[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
@@ -990,6 +990,27 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetail> for CardDetailFromLocker {
+ fn from(item: CardDetail) -> Self {
+ Self {
+ issuer_country: item.card_issuing_country,
+ last4_digits: Some(item.card_number.get_last4()),
+ card_number: Some(item.card_number),
+ expiry_month: Some(item.card_exp_month),
+ expiry_year: Some(item.card_exp_year),
+ card_holder_name: item.card_holder_name,
+ nick_name: item.nick_name,
+ card_isin: None,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type.map(|card| card.to_string()),
+ saved_to_locker: true,
+ card_fingerprint: None,
+ }
+ }
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl From<CardDetail> for CardDetailsPaymentMethod {
fn from(item: CardDetail) -> Self {
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 1f4fd00bbc5..9e70cb2b96b 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -144,6 +144,10 @@ pub const ADD_VAULT_REQUEST_URL: &str = "/vault/add";
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint";
+/// Vault Retrieve request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/vault/retrieve";
+
/// Vault Header content type
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index cb26494b70d..8841ad7f383 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -25,7 +25,7 @@ use common_utils::{consts::DEFAULT_LOCALE, id_type};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use common_utils::{
crypto::{self, Encryptable},
- ext_traits::{AsyncExt, Encode, ValueExt},
+ ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
fp_utils::when,
generate_id,
request::RequestContent,
@@ -80,7 +80,7 @@ const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";
#[instrument(skip_all)]
-pub async fn retrieve_payment_method(
+pub async fn retrieve_payment_method_core(
pm_data: &Option<domain::PaymentMethodData>,
state: &SessionState,
payment_intent: &PaymentIntent,
@@ -877,16 +877,24 @@ pub async fn create_payment_method(
.await
.attach_printable("Failed to add Payment method to DB")?;
- let vaulting_result =
- vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+ let payment_method_data = pm_types::PaymentMethodVaultingData::from(req.payment_method_data);
+
+ let vaulting_result = vault_payment_method(
+ state,
+ &payment_method_data,
+ merchant_account,
+ key_store,
+ None,
+ )
+ .await;
let response = match vaulting_result {
Ok(resp) => {
let pm_update = create_pm_additional_data_update(
- &req.payment_method_data,
+ &payment_method_data,
state,
key_store,
- Some(resp.vault_id),
+ Some(resp.vault_id.get_string_repr().clone()),
Some(req.payment_method),
Some(req.payment_method_type),
)
@@ -1041,16 +1049,24 @@ pub async fn payment_method_intent_confirm(
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
- let vaulting_result =
- vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+ let payment_method_data = pm_types::PaymentMethodVaultingData::from(req.payment_method_data);
+
+ let vaulting_result = vault_payment_method(
+ state,
+ &payment_method_data,
+ merchant_account,
+ key_store,
+ None,
+ )
+ .await;
let response = match vaulting_result {
Ok(resp) => {
let pm_update = create_pm_additional_data_update(
- &req.payment_method_data,
+ &payment_method_data,
state,
key_store,
- Some(resp.vault_id),
+ Some(resp.vault_id.get_string_repr().clone()),
Some(req.payment_method),
Some(req.payment_method_type),
)
@@ -1220,15 +1236,17 @@ pub async fn create_payment_method_for_intent(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub async fn create_pm_additional_data_update(
- pmd: &api::PaymentMethodCreateData,
+ pmd: &pm_types::PaymentMethodVaultingData,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
vault_id: Option<String>,
payment_method: Option<api_enums::PaymentMethod>,
payment_method_type: Option<api_enums::PaymentMethodType>,
) -> RouterResult<storage::PaymentMethodUpdate> {
- let card = match pmd.clone() {
- api::PaymentMethodCreateData::Card(card) => api::PaymentMethodsData::Card(card.into()),
+ let card = match pmd {
+ pm_types::PaymentMethodVaultingData::Card(card) => {
+ api::PaymentMethodsData::Card(card.clone().into())
+ }
};
let pmd: Encryptable<Secret<serde_json::Value>> =
@@ -1255,15 +1273,17 @@ pub async fn create_pm_additional_data_update(
#[instrument(skip_all)]
pub async fn vault_payment_method(
state: &SessionState,
- pmd: &api::PaymentMethodCreateData,
+ pmd: &pm_types::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
+ existing_vault_id: Option<String>,
) -> RouterResult<pm_types::AddVaultResponse> {
let db = &*state.store;
// get fingerprint_id from locker
let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd)
.await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get fingerprint_id from vault")?;
// throw back error if payment method is duplicated
@@ -1286,7 +1306,10 @@ pub async fn vault_payment_method(
)?;
let resp_from_locker =
- cards::vault_payment_method_in_locker(state, merchant_account, pmd).await?;
+ cards::vault_payment_method_in_locker(state, merchant_account, pmd, existing_vault_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to vault payment method in locker")?;
Ok(resp_from_locker)
}
@@ -1656,6 +1679,152 @@ async fn generate_saved_pm_response(
Ok(pma)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method(
+ state: SessionState,
+ pm: api::PaymentMethodId,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+) -> RouterResponse<api::PaymentMethodResponse> {
+ let db = state.store.as_ref();
+ let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = db
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let pmd = payment_method
+ .payment_method_data
+ .clone()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<api::PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ api::PaymentMethodsData::Card(card) => {
+ Some(api::PaymentMethodResponseData::Card(card.into()))
+ }
+ _ => None,
+ });
+
+ let resp = api::PaymentMethodResponse {
+ merchant_id: payment_method.merchant_id.to_owned(),
+ customer_id: payment_method.customer_id.to_owned(),
+ payment_method_id: payment_method.id.get_string_repr().to_string(),
+ payment_method: payment_method.payment_method,
+ payment_method_type: payment_method.payment_method_type,
+ metadata: payment_method.metadata.clone(),
+ created: Some(payment_method.created_at),
+ recurring_enabled: false,
+ last_used_at: Some(payment_method.last_used_at),
+ client_secret: payment_method.client_secret.clone(),
+ payment_method_data: pmd,
+ };
+
+ Ok(services::ApplicationResponse::Json(resp))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn update_payment_method(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ req: api::PaymentMethodUpdate,
+ payment_method_id: &str,
+ key_store: domain::MerchantKeyStore,
+) -> RouterResponse<api::PaymentMethodResponse> {
+ let db = state.store.as_ref();
+
+ let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(payment_method_id.to_string())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = db
+ .find_payment_method(
+ &((&state).into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let current_vault_id = payment_method.locker_id.clone();
+
+ when(
+ payment_method.status == enums::PaymentMethodStatus::AwaitingData,
+ || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "This Payment method is awaiting data and hence cannot be updated"
+ .to_string(),
+ })
+ },
+ )?;
+
+ let pmd: pm_types::PaymentMethodVaultingData = cards::retrieve_payment_method_from_vault(
+ &state,
+ &merchant_account,
+ &payment_method.customer_id,
+ &payment_method,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to retrieve payment method from vault")?
+ .data
+ .expose()
+ .parse_struct("PaymentMethodCreateData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse PaymentMethodCreateData")?;
+
+ let vault_request_data =
+ pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, req.payment_method_data);
+
+ let vaulting_response = vault_payment_method(
+ &state,
+ &vault_request_data,
+ &merchant_account,
+ &key_store,
+ current_vault_id, // using current vault_id for now, will have to refactor this
+ ) // to generate new one on each vaulting later on
+ .await
+ .attach_printable("Failed to add payment method in vault")?;
+
+ let pm_update = create_pm_additional_data_update(
+ &vault_request_data,
+ &state,
+ &key_store,
+ Some(vaulting_response.vault_id.get_string_repr().clone()),
+ payment_method.payment_method,
+ payment_method.payment_method_type,
+ )
+ .await
+ .attach_printable("Unable to create Payment method data")?;
+
+ let payment_method = db
+ .update_payment_method(
+ &((&state).into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ let response = pm_transforms::generate_payment_method_response(&payment_method)?;
+
+ // Add a PT task to handle payment_method delete from vault
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl pm_types::SavedPMLPaymentsInfo {
pub async fn form_payments_info(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index a7ae7f9ca50..578655a927d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1418,26 +1418,26 @@ pub async fn get_fingerprint_id_from_locker<
>(
state: &routes::SessionState,
data: &D,
-) -> errors::RouterResult<String> {
+) -> errors::CustomResult<String, errors::VaultError> {
let key = data.get_vaulting_data_key();
let data = serde_json::to_value(data)
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode Vaulting data to value")?
.to_string();
let payload = pm_types::VaultFingerprintRequest { key, data }
.encode_to_vec()
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultFingerprintRequest")?;
let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::VaultAPIError)
.attach_printable("Failed to get response from locker")?;
let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
.parse_struct("VaultFingerprintResp")
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into VaultFingerprintResp")?;
Ok(fingerprint_resp.fingerprint_id)
@@ -1448,31 +1448,70 @@ pub async fn get_fingerprint_id_from_locker<
pub async fn vault_payment_method_in_locker(
state: &routes::SessionState,
merchant_account: &domain::MerchantAccount,
- pmd: &api::PaymentMethodCreateData,
-) -> errors::RouterResult<pm_types::AddVaultResponse> {
+ pmd: &pm_types::PaymentMethodVaultingData,
+ existing_vault_id: Option<String>,
+) -> errors::CustomResult<pm_types::AddVaultResponse, errors::VaultError> {
let payload = pm_types::AddVaultRequest {
entity_id: merchant_account.get_id().to_owned(),
- vault_id: uuid::Uuid::now_v7().to_string(),
- data: pmd.clone(),
+ vault_id: pm_types::VaultId::generate(
+ existing_vault_id.unwrap_or(uuid::Uuid::now_v7().to_string()),
+ ),
+ data: pmd,
ttl: state.conf.locker.ttl_for_storage_in_secs,
}
.encode_to_vec()
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode AddVaultRequest")?;
let resp = call_to_vault::<pm_types::AddVault>(state, payload)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::VaultAPIError)
.attach_printable("Failed to get response from locker")?;
let stored_pm_resp: pm_types::AddVaultResponse = resp
.parse_struct("AddVaultResponse")
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to parse data into AddVaultResponse")?;
Ok(stored_pm_resp)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn retrieve_payment_method_from_vault(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ customer_id: &id_type::CustomerId,
+ pm: &domain::PaymentMethod,
+) -> errors::CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> {
+ let payload = pm_types::VaultRetrieveRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id: pm_types::VaultId::generate(
+ pm.locker_id
+ .clone()
+ .ok_or(errors::VaultError::MissingRequiredField {
+ field_name: "locker_id",
+ })
+ .attach_printable("Missing locker_id for VaultRetrieveRequest")?,
+ ),
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultRetrieveRequest")?;
+
+ let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Failed to get response from locker")?;
+
+ let stored_pm_resp: pm_types::VaultRetrieveResponse = resp
+ .parse_struct("VaultRetrieveResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultRetrieveResponse")?;
+
+ Ok(stored_pm_resp)
+}
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -1783,18 +1822,6 @@ pub async fn update_customer_payment_method(
}
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn update_customer_payment_method(
- _state: routes::SessionState,
- _merchant_account: domain::MerchantAccount,
- _req: api::PaymentMethodUpdate,
- _payment_method_id: &str,
- _key_store: domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
-}
-
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -5378,17 +5405,6 @@ pub async fn retrieve_payment_method(
))
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn retrieve_payment_method(
- state: routes::SessionState,
- pm: api::PaymentMethodId,
- key_store: domain::MerchantKeyStore,
- merchant_account: domain::MerchantAccount,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
-}
-
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2")
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index ab21add60a8..78770c34579 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -15,6 +15,8 @@ use josekit::jwe;
use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::types::payment_methods as pm_types;
use crate::{
configs::settings,
core::errors::{self, CustomResult},
@@ -520,6 +522,29 @@ pub fn mk_add_card_response_hs(
todo!()
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn generate_pm_vaulting_req_from_update_request(
+ pm_create: pm_types::PaymentMethodVaultingData,
+ pm_update: api::PaymentMethodUpdateData,
+) -> pm_types::PaymentMethodVaultingData {
+ match (pm_create, pm_update) {
+ (
+ pm_types::PaymentMethodVaultingData::Card(card_create),
+ api::PaymentMethodUpdateData::Card(update_card),
+ ) => pm_types::PaymentMethodVaultingData::Card(api::CardDetail {
+ card_number: card_create.card_number,
+ card_exp_month: card_create.card_exp_month,
+ card_exp_year: card_create.card_exp_year,
+ card_issuing_country: card_create.card_issuing_country,
+ card_network: card_create.card_network,
+ card_issuer: card_create.card_issuer,
+ card_type: card_create.card_type,
+ card_holder_name: update_card.card_holder_name,
+ nick_name: update_card.nick_name,
+ }),
+ }
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub fn generate_payment_method_response(
pm: &domain::PaymentMethod,
@@ -798,6 +823,15 @@ pub fn get_card_detail(
Ok(card_detail)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<api::PaymentMethodCreateData> for pm_types::PaymentMethodVaultingData {
+ fn from(item: api::PaymentMethodCreateData) -> Self {
+ match item {
+ api::PaymentMethodCreateData::Card(card) => Self::Card(card),
+ }
+ }
+}
+
//------------------------------------------------TokenizeService------------------------------------------------
pub fn mk_crud_locker_request(
locker: &settings::Locker,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 23ac67c910d..4e484bda6c4 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2226,15 +2226,16 @@ pub async fn make_pm_data<'a, F: Clone, R, D>(
}
(Some(_), _) => {
- let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method(
- &request,
- state,
- &payment_data.payment_intent,
- &payment_data.payment_attempt,
- merchant_key_store,
- Some(business_profile),
- )
- .await?;
+ let (payment_method_data, payment_token) =
+ payment_methods::retrieve_payment_method_core(
+ &request,
+ state,
+ &payment_data.payment_intent,
+ &payment_data.payment_attempt,
+ merchant_key_store,
+ Some(business_profile),
+ )
+ .await?;
payment_data.token = payment_token;
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 9ff768c56fb..d5f73921a9d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1087,7 +1087,12 @@ impl PaymentMethods {
.service(
web::resource("/{id}/confirm-intent")
.route(web::post().to(confirm_payment_method_intent_api)),
- );
+ )
+ .service(
+ web::resource("/{id}/update_saved_payment_method")
+ .route(web::patch().to(payment_method_update_api)),
+ )
+ .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api)));
route
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 725d6af81af..3e3aada154f 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -15,7 +15,7 @@ use super::app::{AppState, SessionState};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use crate::core::payment_methods::{
create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm,
- payment_method_intent_create,
+ payment_method_intent_create, retrieve_payment_method, update_payment_method,
};
use crate::{
core::{
@@ -180,6 +180,65 @@ pub async fn confirm_payment_method_intent_api(
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
+pub async fn payment_method_update_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ json_payload: web::Json<payment_methods::PaymentMethodUpdate>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsUpdate;
+ let payment_method_id = path.into_inner();
+ let payload = json_payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ update_payment_method(
+ state,
+ auth.merchant_account,
+ req,
+ &payment_method_id,
+ auth.key_store,
+ )
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
+pub async fn payment_method_retrieve_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsRetrieve;
+ let payload = web::Json(PaymentMethodId {
+ payment_method_id: path.into_inner(),
+ })
+ .into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, pm, _| {
+ retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account)
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
@@ -667,6 +726,10 @@ pub async fn render_pm_collect_link(
.await
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))]
pub async fn payment_method_retrieve_api(
state: web::Data<AppState>,
@@ -693,6 +756,10 @@ pub async fn payment_method_retrieve_api(
.await
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))]
pub async fn payment_method_update_api(
state: web::Data<AppState>,
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 28d387771b5..d66bf079d42 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -8,8 +8,8 @@ pub use api_models::payment_methods::{
PaymentMethodIntentConfirm, PaymentMethodIntentConfirmInternal, PaymentMethodIntentCreate,
PaymentMethodList, PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate,
- PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1,
- TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
+ TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
};
#[cfg(all(
any(feature = "v2", feature = "v1"),
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
index e55516fc3af..a1c0f8156fa 100644
--- a/crates/router/src/types/payment_methods.rs
+++ b/crates/router/src/types/payment_methods.rs
@@ -1,5 +1,7 @@
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use common_utils::generate_id;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use masking::Secret;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use crate::{
@@ -19,6 +21,21 @@ pub trait VaultingDataInterface {
fn get_vaulting_data_key(&self) -> String;
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultId(String);
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl VaultId {
+ pub fn get_string_repr(&self) -> &String {
+ &self.0
+ }
+
+ pub fn generate(id: String) -> Self {
+ Self(id)
+ }
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequest {
@@ -36,7 +53,7 @@ pub struct VaultFingerprintResponse {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultRequest<D> {
pub entity_id: common_utils::id_type::MerchantId,
- pub vault_id: String,
+ pub vault_id: VaultId,
pub data: D,
pub ttl: i64,
}
@@ -45,7 +62,7 @@ pub struct AddVaultRequest<D> {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultResponse {
pub entity_id: common_utils::id_type::MerchantId,
- pub vault_id: String,
+ pub vault_id: VaultId,
pub fingerprint_id: Option<String>,
}
@@ -57,6 +74,10 @@ pub struct AddVault;
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetVaultFingerprint;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultRetrieve;
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[async_trait::async_trait]
impl VaultingInterface for AddVault {
@@ -75,7 +96,21 @@ impl VaultingInterface for GetVaultFingerprint {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[async_trait::async_trait]
-impl VaultingDataInterface for api::PaymentMethodCreateData {
+impl VaultingInterface for VaultRetrieve {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::VAULT_RETRIEVE_REQUEST_URL
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub enum PaymentMethodVaultingData {
+ Card(api::CardDetail),
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingDataInterface for PaymentMethodVaultingData {
fn get_vaulting_data_key(&self) -> String {
match &self {
Self::Card(card) => card.card_number.to_string(),
@@ -101,3 +136,16 @@ pub struct SavedPMLPaymentsInfo {
pub off_session_payment_flag: bool,
pub is_connector_agnostic_mit_enabled: bool,
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultRetrieveRequest {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: VaultId,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultRetrieveResponse {
+ pub data: Secret<String>,
+}
| 2024-09-18T08:09:47Z |
## Description
<!-- Describe your changes in detail -->
- Update PM API for v2
- Retrieve PM API for v2
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
Vault dev is incomplete so cannot be tested. | 4eec6ca4b05202dea1f5400007c5f143142b65e4 |
Vault dev is incomplete so cannot be tested.
| [
"crates/api_models/src/payment_methods.rs",
"crates/router/src/consts.rs",
"crates/router/src/core/payment_methods.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payment_methods/transformers.rs",
"crates/router/src/core/payments/helpers.rs",
"crates/router/src/routes/app... | |
juspay/hyperswitch | juspay__hyperswitch-5934 | Bug: feat(opensearch): restrict search view access based on user roles and permissions
To fix the issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/6759](https://github.com/juspay/hyperswitch-cloud/issues/6759)
- Currently, a profile level user is able to see the other profile payments list when using global-search, irrespective of whether he has permissions or not. But the user will not be able to view the details related to the payments upon clicking the particular payment.
- This behaviour should be fixed by restricting the profiles / merchants to be searched based on the user roles associated with the role_id and the permissions associated with the user role
- Now, only if the use role has the necessary READ permissions to access the indexes, he would be able to search the payments related to that particular profile/merchant.
-
The search_params should now be constructed with only those ProfileLevel / MerchantLevel / OrgLevel entities which will be searched through the opensearch query. | diff --git a/config/dashboard.toml b/config/dashboard.toml
index 4cafdd49ab3..87c00721736 100644
--- a/config/dashboard.toml
+++ b/config/dashboard.toml
@@ -35,5 +35,6 @@ global_search=true
dispute_analytics=true
configure_pmts=false
branding=false
+user_management_revamp=true
totp=true
live_users_counter=false
\ No newline at end of file
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 149c77212a0..3be9688d8f7 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -104,6 +104,8 @@ pub enum OpenSearchError {
IndexAccessNotPermittedError(SearchIndex),
#[error("Opensearch unknown error")]
UnknownError,
+ #[error("Opensearch access forbidden error")]
+ AccessForbiddenError,
}
impl ErrorSwitch<OpenSearchError> for QueryBuildingError {
@@ -159,6 +161,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError {
Self::UnknownError => {
ApiErrorResponse::InternalServerError(ApiError::new("IR", 6, "Unknown error", None))
}
+ Self::AccessForbiddenError => ApiErrorResponse::ForbiddenCommonResource(ApiError::new(
+ "IR",
+ 7,
+ "Access Forbidden error",
+ None,
+ )),
}
}
}
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index a0b6606c227..89159bcff86 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -1,6 +1,11 @@
pub use analytics::*;
pub mod routes {
+ use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+ };
+
use actix_web::{web, Responder, Scope};
use analytics::{
api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo,
@@ -21,13 +26,13 @@ pub mod routes {
GetSdkEventMetricRequest, ReportRequest,
};
use common_enums::EntityType;
- use common_utils::id_type::{MerchantId, OrganizationId};
use error_stack::{report, ResultExt};
+ use futures::{stream::FuturesUnordered, StreamExt};
use crate::{
- consts::opensearch::OPENSEARCH_INDEX_PERMISSIONS,
+ consts::opensearch::SEARCH_INDEXES,
core::{api_locking, errors::user::UserErrors, verification::utils},
- db::user::UserInterface,
+ db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload},
routes::AppState,
services::{
api,
@@ -35,7 +40,7 @@ pub mod routes {
authorization::{permissions::Permission, roles::RoleInfo},
ApplicationResponse,
},
- types::domain::UserEmail,
+ types::{domain::UserEmail, storage::UserRole},
};
pub struct Analytics;
@@ -1838,25 +1843,89 @@ pub mod routes {
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?;
- let permissions = role_info.get_permissions_set();
- let accessible_indexes: Vec<_> = OPENSEARCH_INDEX_PERMISSIONS
+ let permission_groups = role_info.get_permission_groups();
+ if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) {
+ return Err(OpenSearchError::AccessForbiddenError)?;
+ }
+ let user_roles: HashSet<UserRole> = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &auth.user_id,
+ org_id: Some(&auth.org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: None,
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)?
+ .into_iter()
+ .collect();
+
+ let state = Arc::new(state);
+ let role_info_map: HashMap<String, RoleInfo> = user_roles
.iter()
- .filter(|(_, perm)| perm.iter().any(|p| permissions.contains(p)))
- .map(|(i, _)| *i)
+ .map(|user_role| {
+ let state = Arc::clone(&state);
+ let role_id = user_role.role_id.clone();
+ let org_id = user_role.org_id.clone().unwrap_or_default();
+ async move {
+ RoleInfo::from_role_id_in_org_scope(&state, &role_id, &org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)
+ .map(|role_info| (role_id, role_info))
+ }
+ })
+ .collect::<FuturesUnordered<_>>()
+ .collect::<Vec<_>>()
+ .await
+ .into_iter()
+ .collect::<Result<HashMap<_, _>, _>>()?;
+
+ let filtered_user_roles: Vec<&UserRole> = user_roles
+ .iter()
+ .filter(|user_role| {
+ let user_role_id = &user_role.role_id;
+ if let Some(role_info) = role_info_map.get(user_role_id) {
+ let permissions = role_info.get_permission_groups();
+ permissions.contains(&common_enums::PermissionGroup::OperationsView)
+ } else {
+ false
+ }
+ })
.collect();
- let merchant_id: MerchantId = auth.merchant_id;
- let org_id: OrganizationId = auth.org_id;
- let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel {
- org_id: org_id.clone(),
- merchant_ids: vec![merchant_id.clone()],
- }];
+ let search_params: Vec<AuthInfo> = filtered_user_roles
+ .iter()
+ .filter_map(|user_role| {
+ user_role
+ .get_entity_id_and_type()
+ .and_then(|(_, entity_type)| match entity_type {
+ EntityType::Profile => Some(AuthInfo::ProfileLevel {
+ org_id: user_role.org_id.clone()?,
+ merchant_id: user_role.merchant_id.clone()?,
+ profile_ids: vec![user_role.profile_id.clone()?],
+ }),
+ EntityType::Merchant => Some(AuthInfo::MerchantLevel {
+ org_id: user_role.org_id.clone()?,
+ merchant_ids: vec![user_role.merchant_id.clone()?],
+ }),
+ EntityType::Organization => Some(AuthInfo::OrgLevel {
+ org_id: user_role.org_id.clone()?,
+ }),
+ })
+ })
+ .collect();
analytics::search::msearch_results(
&state.opensearch_client,
req,
search_params,
- accessible_indexes,
+ SEARCH_INDEXES.to_vec(),
)
.await
.map(ApplicationResponse::Json)
@@ -1898,20 +1967,82 @@ pub mod routes {
.await
.change_context(UserErrors::InternalServerError)
.change_context(OpenSearchError::UnknownError)?;
- let permissions = role_info.get_permissions_set();
- let _ = OPENSEARCH_INDEX_PERMISSIONS
+ let permission_groups = role_info.get_permission_groups();
+ if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) {
+ return Err(OpenSearchError::AccessForbiddenError)?;
+ }
+ let user_roles: HashSet<UserRole> = state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: &auth.user_id,
+ org_id: Some(&auth.org_id),
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: None,
+ limit: None,
+ })
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)?
+ .into_iter()
+ .collect();
+ let state = Arc::new(state);
+ let role_info_map: HashMap<String, RoleInfo> = user_roles
.iter()
- .filter(|(ind, _)| *ind == index)
- .find(|i| i.1.iter().any(|p| permissions.contains(p)))
- .ok_or(OpenSearchError::IndexAccessNotPermittedError(index))?;
+ .map(|user_role| {
+ let state = Arc::clone(&state);
+ let role_id = user_role.role_id.clone();
+ let org_id = user_role.org_id.clone().unwrap_or_default();
+ async move {
+ RoleInfo::from_role_id_in_org_scope(&state, &role_id, &org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)
+ .map(|role_info| (role_id, role_info))
+ }
+ })
+ .collect::<FuturesUnordered<_>>()
+ .collect::<Vec<_>>()
+ .await
+ .into_iter()
+ .collect::<Result<HashMap<_, _>, _>>()?;
- let merchant_id: MerchantId = auth.merchant_id;
- let org_id: OrganizationId = auth.org_id;
- let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel {
- org_id: org_id.clone(),
- merchant_ids: vec![merchant_id.clone()],
- }];
+ let filtered_user_roles: Vec<&UserRole> = user_roles
+ .iter()
+ .filter(|user_role| {
+ let user_role_id = &user_role.role_id;
+ if let Some(role_info) = role_info_map.get(user_role_id) {
+ let permissions = role_info.get_permission_groups();
+ permissions.contains(&common_enums::PermissionGroup::OperationsView)
+ } else {
+ false
+ }
+ })
+ .collect();
+ let search_params: Vec<AuthInfo> = filtered_user_roles
+ .iter()
+ .filter_map(|user_role| {
+ user_role
+ .get_entity_id_and_type()
+ .and_then(|(_, entity_type)| match entity_type {
+ EntityType::Profile => Some(AuthInfo::ProfileLevel {
+ org_id: user_role.org_id.clone()?,
+ merchant_id: user_role.merchant_id.clone()?,
+ profile_ids: vec![user_role.profile_id.clone()?],
+ }),
+ EntityType::Merchant => Some(AuthInfo::MerchantLevel {
+ org_id: user_role.org_id.clone()?,
+ merchant_ids: vec![user_role.merchant_id.clone()?],
+ }),
+ EntityType::Organization => Some(AuthInfo::OrgLevel {
+ org_id: user_role.org_id.clone()?,
+ }),
+ })
+ })
+ .collect();
analytics::search::search_results(&state.opensearch_client, req, search_params)
.await
.map(ApplicationResponse::Json)
diff --git a/crates/router/src/consts/opensearch.rs b/crates/router/src/consts/opensearch.rs
index fc1c071439a..277b0e946ba 100644
--- a/crates/router/src/consts/opensearch.rs
+++ b/crates/router/src/consts/opensearch.rs
@@ -1,22 +1,12 @@
use api_models::analytics::search::SearchIndex;
-use crate::services::authorization::permissions::Permission;
-
-pub const OPENSEARCH_INDEX_PERMISSIONS: &[(SearchIndex, &[Permission])] = &[
- (
+pub const fn get_search_indexes() -> [SearchIndex; 4] {
+ [
SearchIndex::PaymentAttempts,
- &[Permission::PaymentRead, Permission::PaymentWrite],
- ),
- (
SearchIndex::PaymentIntents,
- &[Permission::PaymentRead, Permission::PaymentWrite],
- ),
- (
SearchIndex::Refunds,
- &[Permission::RefundRead, Permission::RefundWrite],
- ),
- (
SearchIndex::Disputes,
- &[Permission::DisputeRead, Permission::DisputeWrite],
- ),
-];
+ ]
+}
+
+pub const SEARCH_INDEXES: [SearchIndex; 4] = get_search_indexes();
| 2024-09-18T06:53:54Z |
## Description
<!-- Describe your changes in detail -->
Fixes the issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/6759](https://github.com/juspay/hyperswitch-cloud/issues/6759)
- Currently, a profile level user is able to see the other profile payments list when using global-search, irrespective of whether he has permissions or not. But the user will not be able to view the details related to the payments upon clicking the particular payment.
- This PR fixes this behaviour by restricting the profiles / merchants to be searched based on the user roles associated with the role_id and the permissions associated with the user role
- Now, only if the use role has the necessary READ permissions to access the indexes, he would be able to search the payments related to that particular profile/merchant.
- The `search_params` will now be constructed with only those ProfileLevel / MerchantLevel / OrgLevel entities which will be searched through the opensearch query.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
To preserve confidentiality of the payment details
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Try to search payments of a profile from another profile which doesn't have access to the profile where the payments are present. Results should not show up while using global search. | e7da0474ec63c9953098ee808543e22e114291cf |
Try to search payments of a profile from another profile which doesn't have access to the profile where the payments are present. Results should not show up while using global search.
| [
"config/dashboard.toml",
"crates/analytics/src/opensearch.rs",
"crates/router/src/analytics.rs",
"crates/router/src/consts/opensearch.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5944 | Bug: feat(refunds) : profile level refunds aggregate
Support for disputes aggregate at profile level | diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 118f4b81766..0f3dfa44c10 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1098,11 +1098,17 @@ pub async fn get_filters_for_refunds(
pub async fn get_aggregates_for_refunds(
state: SessionState,
merchant: domain::MerchantAccount,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundAggregateResponse> {
let db = state.store.as_ref();
let refund_status_with_count = db
- .get_refund_status_with_count(merchant.get_id(), &time_range, merchant.storage_scheme)
+ .get_refund_status_with_count(
+ merchant.get_id(),
+ profile_id_list,
+ &time_range,
+ merchant.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find status count")?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index ff7e8145c33..0190718791f 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2546,11 +2546,12 @@ impl RefundInterface for KafkaStore {
async fn get_refund_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
self.diesel_store
- .get_refund_status_with_count(merchant_id, constraints, storage_scheme)
+ .get_refund_status_with_count(merchant_id, profile_id_list, constraints, storage_scheme)
.await
}
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index dbe7534ee28..cf092ad410e 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -88,6 +88,7 @@ pub trait RefundInterface {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>;
@@ -265,11 +266,12 @@ mod storage {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, time_range)
+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range)
.await
.map_err(|error|report!(errors::StorageError::from(error)))
}
@@ -831,11 +833,12 @@ mod storage {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, constraints)
+ <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, constraints)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
@@ -1182,6 +1185,7 @@ impl RefundInterface for MockDb {
async fn get_refund_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> {
@@ -1194,7 +1198,17 @@ impl RefundInterface for MockDb {
let filtered_refunds = refunds
.iter()
- .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time)
+ .filter(|refund| {
+ refund.created_at >= start_time
+ && refund.created_at <= end_time
+ && profile_id_list
+ .as_ref()
+ .zip(refund.profile_id.as_ref())
+ .map(|(received_profile_list, received_profile_id)| {
+ received_profile_list.contains(received_profile_id)
+ })
+ .unwrap_or(true)
+ })
.cloned()
.collect::<Vec<diesel_models::refund::Refund>>();
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 01a48c56401..a8a7ea7d56f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1002,6 +1002,10 @@ impl Refunds {
.service(web::resource("/filter").route(web::post().to(refunds_filter_list)))
.service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters)))
.service(web::resource("/aggregate").route(web::get().to(get_refunds_aggregates)))
+ .service(
+ web::resource("/profile/aggregate")
+ .route(web::get().to(get_refunds_aggregate_profile)),
+ )
.service(
web::resource("/v2/profile/filter")
.route(web::get().to(get_refunds_filters_profile)),
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index 40184c5fcfa..aaea6d4c99e 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -436,7 +436,7 @@ pub async fn get_refunds_aggregates(
&req,
query_params,
|state, auth: auth::AuthenticationData, req, _| {
- get_aggregates_for_refunds(state, auth.merchant_account, req)
+ get_aggregates_for_refunds(state, auth.merchant_account, None, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
@@ -473,3 +473,38 @@ pub async fn refunds_manual_update(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))]
+#[cfg(feature = "olap")]
+pub async fn get_refunds_aggregate_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_params: web::Query<common_utils::types::TimeRange>,
+) -> HttpResponse {
+ let flow = Flow::RefundsAggregate;
+ let query_params = query_params.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_params,
+ |state, auth: auth::AuthenticationData, req, _| {
+ get_aggregates_for_refunds(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Profile,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 350c1032261..8076c2c7a6e 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -41,6 +41,7 @@ pub trait RefundDbExt: Sized {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>;
}
@@ -299,6 +300,7 @@ impl RefundDbExt for Refund {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
@@ -307,6 +309,10 @@ impl RefundDbExt for Refund {
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
+ if let Some(profile_id) = profile_id_list {
+ query = query.filter(dsl::profile_id.eq_any(profile_id));
+ }
+
query = query.filter(dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
| 2024-09-18T06:32:36Z |
## Description
<!-- Describe your changes in detail -->
- Add support for profile level refunds aggregate
- For now it will have list of intent status along with the their count for a given time range.
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request :
```
curl --location 'http://localhost:8080/refunds/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"status_with_count": {
"success": 3,
"pending": 0,
"failure": 0,
"manual_review": 0,
"transaction_failure": 0
}
}
``` | dccb8d4e629d615a69f6922a96e72f10d3410bfc |
Request :
```
curl --location 'http://localhost:8080/refunds/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"status_with_count": {
"success": 3,
"pending": 0,
"failure": 0,
"manual_review": 0,
"transaction_failure": 0
}
}
```
| [
"crates/router/src/core/refunds.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/db/refund.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/refunds.rs",
"crates/router/src/types/storage/refund.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5924 | Bug: [FEATURE] [DEUTSCHEBANK] Implement subsequent mandate payments via SEPA
### Feature Description
Implement SEPA mandate payments for Deutschebank.
### Possible Implementation
Implement SEPA mandate payments for Deutschebank.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index b0866cfb265..535a5abffce 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1042,6 +1042,7 @@ pub struct ConnectorMandateReferenceId {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub update_history: Option<Vec<UpdateHistory>>,
+ pub mandate_metadata: Option<serde_json::Value>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
index 30e67babe89..a861155afb3 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
@@ -50,7 +50,10 @@ use transformers as deutschebank;
use crate::{
constants::headers,
types::ResponseRouterData,
- utils::{self, PaymentsCompleteAuthorizeRequestData, RefundsRequestData},
+ utils::{
+ self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+ RefundsRequestData,
+ },
};
#[derive(Clone)]
@@ -182,6 +185,16 @@ impl ConnectorValidation for Deutschebank {
),
}
}
+
+ fn validate_mandate_payment(
+ &self,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let mandate_supported_pmd =
+ std::collections::HashSet::from([utils::PaymentMethodDataType::SepaBankDebit]);
+ utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ }
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank {
@@ -302,13 +315,26 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
- _req: &PaymentsAuthorizeRouterData,
+ req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!(
- "{}/services/v2.1/managedmandate",
- self.base_url(connectors)
- ))
+ if req.request.connector_mandate_id().is_none() {
+ Ok(format!(
+ "{}/services/v2.1/managedmandate",
+ self.base_url(connectors)
+ ))
+ } else {
+ let event_id = req.connector_request_reference_id.clone();
+ let tx_action = if req.request.is_auto_capture()? {
+ "authorization"
+ } else {
+ "preauthorization"
+ };
+ Ok(format!(
+ "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}",
+ self.base_url(connectors)
+ ))
+ }
}
fn get_request_body(
@@ -356,17 +382,31 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: deutschebank::DeutschebankMandatePostResponse = res
- .response
- .parse_struct("Deutschebank PaymentsAuthorizeResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- RouterData::try_from(ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
+ if data.request.connector_mandate_id().is_none() {
+ let response: deutschebank::DeutschebankMandatePostResponse = res
+ .response
+ .parse_struct("DeutschebankMandatePostResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ } else {
+ let response: deutschebank::DeutschebankPaymentsResponse = res
+ .response
+ .parse_struct("DeutschebankPaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
}
fn get_error_response(
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
index dc146dc38d4..8b3837edd63 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
@@ -1,7 +1,8 @@
use std::collections::HashMap;
use common_enums::enums;
-use common_utils::{pii::Email, types::MinorUnit};
+use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit};
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{AccessToken, ConnectorAuthType, RouterData},
@@ -13,7 +14,9 @@ use hyperswitch_domain_models::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
ResponseId,
},
- router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ router_response_types::{
+ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
+ },
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
@@ -26,8 +29,8 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
- AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- RefundsRequestData, RouterData as OtherRouterData,
+ self, AddressDetailsData, PaymentsAuthorizeRequestData,
+ PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData,
},
};
@@ -113,7 +116,7 @@ pub enum DeutschebankSEPAApproval {
}
#[derive(Debug, Serialize, PartialEq)]
-pub struct DeutschebankPaymentsRequest {
+pub struct DeutschebankMandatePostRequest {
approval_by: DeutschebankSEPAApproval,
email_address: Email,
iban: Secret<String>,
@@ -121,6 +124,13 @@ pub struct DeutschebankPaymentsRequest {
last_name: Secret<String>,
}
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum DeutschebankPaymentsRequest {
+ MandatePost(DeutschebankMandatePostRequest),
+ DirectDebit(DeutschebankDirectDebitRequest),
+}
+
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
for DeutschebankPaymentsRequest
{
@@ -128,16 +138,71 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
- let billing_address = item.router_data.get_billing_address()?;
- match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Self {
- approval_by: DeutschebankSEPAApproval::Click,
- email_address: item.router_data.request.get_email()?,
- iban,
- first_name: billing_address.get_first_name()?.clone(),
- last_name: billing_address.get_last_name()?.clone(),
- }),
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ match item
+ .router_data
+ .request
+ .mandate_id
+ .clone()
+ .and_then(|mandate_id| mandate_id.mandate_reference_id)
+ {
+ None => {
+ if item.router_data.request.is_mandate_payment() {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
+ iban, ..
+ }) => {
+ let billing_address = item.router_data.get_billing_address()?;
+ Ok(Self::MandatePost(DeutschebankMandatePostRequest {
+ approval_by: DeutschebankSEPAApproval::Click,
+ email_address: item.router_data.request.get_email()?,
+ iban,
+ first_name: billing_address.get_first_name()?.clone(),
+ last_name: billing_address.get_last_name()?.clone(),
+ }))
+ }
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("deutschebank"),
+ )
+ .into()),
+ }
+ } else {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "setup_future_usage or customer_acceptance.acceptance_type",
+ }
+ .into())
+ }
+ }
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => {
+ let mandate_metadata: DeutschebankMandateMetadata = mandate_data
+ .mandate_metadata
+ .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)?
+ .clone()
+ .parse_value("DeutschebankMandateMetadata")
+ .change_context(errors::ConnectorError::ParsingFailed)?;
+ Ok(Self::DirectDebit(DeutschebankDirectDebitRequest {
+ amount_total: DeutschebankAmount {
+ amount: item.amount,
+ currency: item.router_data.request.currency,
+ },
+ means_of_payment: DeutschebankMeansOfPayment {
+ bank_account: DeutschebankBankAccount {
+ account_holder: mandate_metadata.account_holder,
+ iban: mandate_metadata.iban,
+ },
+ },
+ mandate: DeutschebankMandate {
+ reference: mandate_metadata.reference,
+ signed_on: mandate_metadata.signed_on,
+ },
+ }))
+ }
+ Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_))
+ | Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("deutschebank"),
+ )
+ .into())
+ }
}
}
}
@@ -176,6 +241,14 @@ impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus {
}
}
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct DeutschebankMandateMetadata {
+ account_holder: Secret<String>,
+ iban: Secret<String>,
+ reference: Secret<String>,
+ signed_on: String,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankMandatePostResponse {
rc: String,
@@ -207,14 +280,14 @@ impl
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let signed_on = match item.response.approval_date {
+ let signed_on = match item.response.approval_date.clone() {
Some(date) => date.chars().take(10).collect(),
None => time::OffsetDateTime::now_utc().date().to_string(),
};
- match item.response.reference {
+ match item.response.reference.clone() {
Some(reference) => Ok(Self {
status: if item.response.rc == "0" {
- match item.response.state {
+ match item.response.state.clone() {
Some(state) => common_enums::AttemptStatus::from(state),
None => common_enums::AttemptStatus::Failure,
}
@@ -227,11 +300,29 @@ impl
endpoint: item.data.request.get_complete_authorize_url()?,
method: common_utils::request::Method::Get,
form_fields: HashMap::from([
- ("reference".to_string(), reference),
- ("signed_on".to_string(), signed_on),
+ ("reference".to_string(), reference.clone()),
+ ("signed_on".to_string(), signed_on.clone()),
]),
}),
- mandate_reference: None,
+ mandate_reference: Some(MandateReference {
+ connector_mandate_id: item.response.mandate_id,
+ payment_method_id: None,
+ mandate_metadata: Some(serde_json::json!(DeutschebankMandateMetadata {
+ account_holder: item.data.get_billing_address()?.get_full_name()?,
+ iban: match item.data.request.payment_method_data.clone() {
+ PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit {
+ iban,
+ ..
+ }) => Ok(iban),
+ _ => Err(errors::ConnectorError::MissingRequiredField {
+ field_name:
+ "payment_method_data.bank_debit.sepa_bank_debit.iban"
+ }),
+ }?,
+ reference: Secret::from(reference),
+ signed_on,
+ })),
+ }),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -248,6 +339,49 @@ impl
}
}
+impl
+ TryFrom<
+ ResponseRouterData<
+ Authorize,
+ DeutschebankPaymentsResponse,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ Authorize,
+ DeutschebankPaymentsResponse,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: if item.response.rc == "0" {
+ match item.data.request.is_auto_capture()? {
+ true => common_enums::AttemptStatus::Charged,
+ false => common_enums::AttemptStatus::Authorized,
+ }
+ } else {
+ common_enums::AttemptStatus::Failure
+ },
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankAmount {
amount: MinorUnit,
@@ -268,7 +402,7 @@ pub struct DeutschebankBankAccount {
#[derive(Debug, Serialize, PartialEq)]
pub struct DeutschebankMandate {
reference: Secret<String>,
- signed_on: Secret<String>,
+ signed_on: String,
}
#[derive(Debug, Serialize, PartialEq)]
@@ -319,14 +453,12 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
})?
.to_owned(),
);
- let signed_on = Secret::from(
- queries_params
- .get("signed_on")
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "signed_on",
- })?
- .to_owned(),
- );
+ let signed_on = queries_params
+ .get("signed_on")
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "signed_on",
+ })?
+ .to_owned();
match item.router_data.request.payment_method_data.clone() {
Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => {
@@ -349,7 +481,10 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
},
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("deutschebank"),
+ )
+ .into()),
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
index fdec3d0e1eb..7f88903e867 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
@@ -170,13 +170,6 @@ pub enum ResponseType {
UnsupportedMediaType,
}
-#[derive(Debug, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub enum FiservemeaResponseType {
- TransactionResponse,
- ErrorResponse,
-}
-
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FiservemeaTransactionType {
@@ -329,7 +322,7 @@ fn map_status(
pub struct FiservemeaPaymentsResponse {
response_type: Option<ResponseType>,
#[serde(rename = "type")]
- fiservemea_type: Option<FiservemeaResponseType>,
+ fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
ipg_transaction_id: String,
@@ -526,7 +519,7 @@ pub struct FiservemeaError {
#[derive(Debug, Serialize, Deserialize)]
pub struct FiservemeaErrorResponse {
#[serde(rename = "type")]
- fiservemea_type: Option<FiservemeaResponseType>,
+ fiservemea_type: Option<String>,
client_request_id: Option<String>,
api_trace_id: Option<String>,
pub response_type: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
index b400555305d..56da53c2873 100644
--- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -787,6 +787,7 @@ impl<F>
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
+ mandate_metadata: None,
}
}),
connector_metadata: None,
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index df0b63833d9..a9451f6156a 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -242,6 +242,7 @@ pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
+ pub mandate_metadata: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index cb682514c83..79a78efb538 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -82,6 +82,7 @@ pub struct TaxCalculationResponseData {
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
+ pub mandate_metadata: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs
index e36707af6b0..06f197ebf0b 100644
--- a/crates/hyperswitch_interfaces/src/errors.rs
+++ b/crates/hyperswitch_interfaces/src/errors.rs
@@ -56,6 +56,8 @@ pub enum ConnectorError {
CaptureMethodNotSupported,
#[error("Missing connector mandate ID")]
MissingConnectorMandateID,
+ #[error("Missing connector mandate metadata")]
+ MissingConnectorMandateMetadata,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 5842143ad44..46f312b38f2 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -746,6 +746,7 @@ impl<F, T>
.map(|id| types::MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(Self {
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index e915d05c358..361ebece299 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3294,6 +3294,7 @@ pub fn get_adyen_response(
.map(|mandate_id| types::MandateReference {
connector_mandate_id: Some(mandate_id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
let network_txn_id = response.additional_data.and_then(|additional_data| {
additional_data
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 57563c276f5..868409dafc7 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -398,6 +398,7 @@ impl<F, T>
format!("{customer_profile_id}-{payment_profile_id}")
}),
payment_method_id: None,
+ mandate_metadata: None,
},
),
connector_metadata: None,
@@ -1109,6 +1110,7 @@ impl<F, T>
},
),
payment_method_id: None,
+ mandate_metadata: None,
}
});
diff --git a/crates/router/src/connector/bamboraapac/transformers.rs b/crates/router/src/connector/bamboraapac/transformers.rs
index 3c197699309..819c918338e 100644
--- a/crates/router/src/connector/bamboraapac/transformers.rs
+++ b/crates/router/src/connector/bamboraapac/transformers.rs
@@ -280,6 +280,7 @@ impl<F>
Some(types::MandateReference {
connector_mandate_id,
payment_method_id: None,
+ mandate_metadata: None,
})
} else {
None
@@ -463,6 +464,7 @@ impl<F>
mandate_reference: Some(types::MandateReference {
connector_mandate_id: Some(connector_mandate_id),
payment_method_id: None,
+ mandate_metadata: None,
}),
connector_metadata: None,
network_txn_id: None,
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 46a522c7378..f47ab4139e8 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -359,6 +359,7 @@ impl<F, T>
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
}
});
let mut mandate_status =
@@ -1487,6 +1488,7 @@ fn get_payment_response(
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(types::PaymentsResponseData::TransactionResponse {
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 22982ceb213..05d8c1c559d 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -443,6 +443,7 @@ impl<F>
MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
+ mandate_metadata: None,
}
}),
connector_metadata: None,
@@ -617,6 +618,7 @@ impl<F>
MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
+ mandate_metadata: None,
}
}),
connector_metadata: None,
@@ -698,6 +700,7 @@ impl<F>
MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
+ mandate_metadata: None,
}
}),
connector_metadata: None,
@@ -761,6 +764,7 @@ impl<F>
MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
+ mandate_metadata: None,
}
}),
connector_metadata: None,
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index fc35cab773a..9ad4f0604a4 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -2227,6 +2227,7 @@ fn get_payment_response(
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -2947,6 +2948,7 @@ impl
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
let mut mandate_status = enums::AttemptStatus::foreign_from((
item.response
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index efc6661b447..19568ae4671 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -261,6 +261,7 @@ fn get_payment_response(
.map(|id| types::MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
})
});
match status {
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index f3250602dbc..ff2f9d95026 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -512,6 +512,7 @@ impl<F>
let mandate_reference = Some(MandateReference {
connector_mandate_id: Some(item.response.mandates.id.clone().expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -664,6 +665,7 @@ impl<F>
let mandate_reference = MandateReference {
connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?),
payment_method_id: None,
+ mandate_metadata: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.payments.status),
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index c44cf14ab65..547a38ad849 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -982,6 +982,7 @@ impl<F, T>
.map(|id| types::MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
}),
connector_metadata: None,
network_txn_id: None,
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 43cb4cecec8..55b2fbe4176 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -358,6 +358,7 @@ impl<F, T>
.map(|id| types::MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(Self {
status: enums::AttemptStatus::foreign_from((
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index b7df6829da4..5d987174273 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -574,6 +574,7 @@ impl<F, T>
.map(|subscription_data| types::MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(Self {
status,
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 2547443484e..f280d3a42a2 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1602,6 +1602,7 @@ where
.map(|id| types::MandateReference {
connector_mandate_id: Some(id),
payment_method_id: None,
+ mandate_metadata: None,
}),
// we don't need to save session token for capture, void flow so ignoring if it is not present
connector_metadata: if let Some(token) = response.session_token {
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 0bb10c9845a..8c2ad2ef979 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -418,6 +418,7 @@ impl<F, T>
.map(|id| types::MandateReference {
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
let status = enums::AttemptStatus::foreign_from((
item.response.transaction_status,
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index c12e478b08e..e0ab598d76d 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -250,6 +250,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData {
mandate_reference: value.buyer_key.clone().map(|buyer_key| MandateReference {
connector_mandate_id: Some(buyer_key.expose()),
payment_method_id: None,
+ mandate_metadata: None,
}),
connector_metadata: None,
network_txn_id: None,
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 910cb94e929..2129ad327c2 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2389,6 +2389,7 @@ impl<F, T>
types::MandateReference {
connector_mandate_id,
payment_method_id,
+ mandate_metadata: None,
}
});
@@ -2583,6 +2584,7 @@ impl<F, T>
types::MandateReference {
connector_mandate_id,
payment_method_id: Some(payment_method_id),
+ mandate_metadata: None,
}
});
@@ -2673,6 +2675,7 @@ impl<F, T>
types::MandateReference {
connector_mandate_id,
payment_method_id,
+ mandate_metadata: None,
}
});
let status = enums::AttemptStatus::from(item.response.status);
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index 761fc43982b..be3cf4a1cef 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -1778,6 +1778,7 @@ fn get_payment_response(
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -1963,6 +1964,7 @@ impl
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
payment_method_id: None,
+ mandate_metadata: None,
});
let mut mandate_status = enums::AttemptStatus::foreign_from((
item.response
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index d2812447ed8..549857494f0 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -189,6 +189,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::CaptureMethodNotSupported
| errors::ConnectorError::MissingConnectorMandateID
+ | errors::ConnectorError::MissingConnectorMandateMetadata
| errors::ConnectorError::MissingConnectorTransactionID
| errors::ConnectorError::MissingConnectorRefundID
| errors::ConnectorError::MissingApplePayTokenData
@@ -288,6 +289,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
errors::ConnectorError::FailedToObtainCertificateKey |
errors::ConnectorError::CaptureMethodNotSupported |
errors::ConnectorError::MissingConnectorMandateID |
+ errors::ConnectorError::MissingConnectorMandateMetadata |
errors::ConnectorError::MissingConnectorTransactionID |
errors::ConnectorError::MissingConnectorRefundID |
errors::ConnectorError::MissingApplePayTokenData |
@@ -376,6 +378,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::CaptureMethodNotSupported
| errors::ConnectorError::MissingConnectorMandateID
+ | errors::ConnectorError::MissingConnectorMandateMetadata
| errors::ConnectorError::MissingConnectorTransactionID
| errors::ConnectorError::MissingConnectorRefundID
| errors::ConnectorError::MissingApplePayTokenData
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 85ae8641373..3a55bf77771 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4093,6 +4093,9 @@ where
payment_method_info.get_id().clone(),
),
update_history: None,
+ mandate_metadata: mandate_reference_record
+ .mandate_metadata
+ .clone(),
},
));
payment_data.set_recurring_mandate_payment_data(
@@ -4103,6 +4106,8 @@ where
.original_payment_authorized_amount,
original_payment_authorized_currency: mandate_reference_record
.original_payment_authorized_currency,
+ mandate_metadata: mandate_reference_record
+ .mandate_metadata.clone(),
});
connector_choice = Some((connector_data, mandate_reference_id.clone()));
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index e9dca13dc80..ac6c236f536 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -802,6 +802,7 @@ pub async fn get_token_for_recurring_mandate(
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
+ mandate_metadata: None,
}),
payment_method_type: payment_method.payment_method_type,
mandate_connector: Some(mandate_connector_details),
@@ -816,6 +817,7 @@ pub async fn get_token_for_recurring_mandate(
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
+ mandate_metadata: None,
}),
payment_method_type: payment_method.payment_method_type,
mandate_connector: Some(mandate_connector_details),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index c75cc29ce51..658a02f7d08 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -681,6 +681,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
),
payment_method_id: None,
update_history: None,
+ mandate_metadata: None,
},
),
),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 0731def9453..4b931d68f1e 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -398,7 +398,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
api_models::payments::ConnectorMandateReferenceId{
connector_mandate_id: connector_id.connector_mandate_id,
payment_method_id: connector_id.payment_method_id,
- update_history: None
+ update_history: None,
+ mandate_metadata: None,
}
))
}
@@ -437,6 +438,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
),
payment_method_id: None,
update_history: None,
+ mandate_metadata: None,
},
),
),
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 90ca49c9746..09292224cae 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1504,21 +1504,24 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let flow_name = core_utils::get_flow_name::<F>()?;
if flow_name == "PSync" || flow_name == "CompleteAuthorize" {
- let connector_mandate_id = match router_data.response.clone() {
+ let (connector_mandate_id, mandate_metadata) = match router_data.response.clone() {
Ok(resp) => match resp {
types::PaymentsResponseData::TransactionResponse {
ref mandate_reference,
..
} => {
if let Some(mandate_ref) = mandate_reference {
- mandate_ref.connector_mandate_id.clone()
+ (
+ mandate_ref.connector_mandate_id.clone(),
+ mandate_ref.mandate_metadata.clone(),
+ )
} else {
- None
+ (None, None)
}
}
- _ => None,
+ _ => (None, None),
},
- Err(_) => None,
+ Err(_) => (None, None),
};
if let Some(payment_method) = payment_data.payment_method_info.clone() {
let connector_mandate_details =
@@ -1529,6 +1532,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
payment_data.payment_attempt.currency,
payment_data.payment_attempt.merchant_connector_id.clone(),
connector_mandate_id,
+ mandate_metadata,
)?;
payment_methods::cards::update_payment_method_connector_mandate_details(
state,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index c5e7cebac34..c69595d1893 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -329,7 +329,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None },
+ api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None, mandate_metadata:connector_id.mandate_metadata, },
))
}
}),
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2d81aecb30e..ca8c6718aa7 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -148,18 +148,21 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
- let connector_mandate_id = match responses {
+ let (connector_mandate_id, mandate_metadata) = match responses {
types::PaymentsResponseData::TransactionResponse {
ref mandate_reference,
..
} => {
if let Some(mandate_ref) = mandate_reference {
- mandate_ref.connector_mandate_id.clone()
+ (
+ mandate_ref.connector_mandate_id.clone(),
+ mandate_ref.mandate_metadata.clone(),
+ )
} else {
- None
+ (None, None)
}
}
- _ => None,
+ _ => (None, None),
};
let check_for_mit_mandates = save_payment_method_data
.request
@@ -178,6 +181,7 @@ where
currency,
merchant_connector_id.clone(),
connector_mandate_id.clone(),
+ mandate_metadata.clone(),
)
} else {
None
@@ -373,6 +377,7 @@ where
currency,
merchant_connector_id.clone(),
connector_mandate_id.clone(),
+ mandate_metadata.clone(),
)?;
payment_methods::cards::update_payment_method_connector_mandate_details(state,
@@ -479,6 +484,7 @@ where
currency,
merchant_connector_id.clone(),
connector_mandate_id.clone(),
+ mandate_metadata.clone(),
)?;
payment_methods::cards::update_payment_method_connector_mandate_details( state,
@@ -1160,6 +1166,7 @@ pub fn add_connector_mandate_details_in_payment_method(
authorized_currency: Option<storage_enums::Currency>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
+ mandate_metadata: Option<serde_json::Value>,
) -> Option<storage::PaymentsMandateReference> {
let mut mandate_details = HashMap::new();
@@ -1173,6 +1180,7 @@ pub fn add_connector_mandate_details_in_payment_method(
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
+ mandate_metadata,
},
);
Some(storage::PaymentsMandateReference(mandate_details))
@@ -1188,6 +1196,7 @@ pub fn update_connector_mandate_details_in_payment_method(
authorized_currency: Option<storage_enums::Currency>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
+ mandate_metadata: Option<serde_json::Value>,
) -> RouterResult<Option<serde_json::Value>> {
let mandate_reference = match payment_method.connector_mandate_details {
Some(_) => {
@@ -1208,6 +1217,7 @@ pub fn update_connector_mandate_details_in_payment_method(
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
+ mandate_metadata: mandate_metadata.clone(),
};
mandate_details.map(|mut payment_mandate_reference| {
payment_mandate_reference
@@ -1218,6 +1228,7 @@ pub fn update_connector_mandate_details_in_payment_method(
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
+ mandate_metadata: mandate_metadata.clone(),
});
payment_mandate_reference
})
@@ -1231,6 +1242,7 @@ pub fn update_connector_mandate_details_in_payment_method(
authorized_currency,
merchant_connector_id,
connector_mandate_id,
+ mandate_metadata,
),
};
let connector_mandate_details = mandate_reference
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 34c5714e126..bb1b801edb6 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -124,6 +124,7 @@ pub struct PaymentsMandateReferenceRecord {
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
+ pub mandate_metadata: Option<serde_json::Value>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
| 2024-09-17T11:42:58Z |
## Description
<!-- Describe your changes in detail -->
Implement SEPA mandate payments for Deutschebank.
These mandate details will be stored in the payment_methods table in the connector_mandate_details.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/5924
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Payments Intent Create:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 1650,
"currency": "EUR",
"confirm": false,
"customer_id": "customer123",
"setup_future_usage": "off_session"
}'
```
Response:
```
{
"payment_id": "pay_u8nPxFlL3ZUW94kkzrI1",
"merchant_id": "merchant_1725539597",
"status": "requires_payment_method",
"amount": 1650,
"net_amount": 1650,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB",
"created": "2024-09-17T12:59:17.770Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726577957,
"expires": 1726581557,
"secret": "epk_46a85e0e97b645a1bb2f838483b3bf70"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:14:17.769Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-17T12:59:17.902Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
2. Payments Confirm:
Request:
```
curl --location 'http://localhost:8080/payments/pay_u8nPxFlL3ZUW94kkzrI1/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data-raw '{
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87123456781234567890"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"email": "something@example.com",
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_u8nPxFlL3ZUW94kkzrI1",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 1650,
"net_amount": 1650,
"amount_capturable": 1650,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB",
"created": "2024-09-17T12:59:17.770Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_K3jaclrwRSo2guy2kfn1",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_u8nPxFlL3ZUW94kkzrI1/merchant_1725539597/pay_u8nPxFlL3ZUW94kkzrI1_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:14:17.769Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_8qqABCQOMAznGanjmLhz",
"payment_method_status": null,
"updated": "2024-09-17T12:59:36.782Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
3. Creating payment using payment_method_id:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 179,
"currency": "EUR",
"confirm": true,
"customer_id": "customer123",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_8qqABCQOMAznGanjmLhz"
},
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_zeindrGrgMlzJscKZdAC",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 179,
"net_amount": 179,
"amount_capturable": 0,
"amount_received": 179,
"connector": "deutschebank",
"client_secret": "pay_zeindrGrgMlzJscKZdAC_secret_W4q8bNJWw2yH7MVaC70L",
"created": "2024-09-17T13:24:07.080Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726579447,
"expires": 1726583047,
"secret": "epk_d80c49dcbeb1431cadf357b9c6d64ad9"
},
"manual_retry_allowed": false,
"connector_transaction_id": "nz17xcQ3x7q7kecPExgV0s",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:39:07.079Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_8qqABCQOMAznGanjmLhz",
"payment_method_status": "active",
"updated": "2024-09-17T13:24:08.282Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
``` | a94cf25bb6eb40fafc5327aceffac8292b47b001 |
1. Payments Intent Create:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 1650,
"currency": "EUR",
"confirm": false,
"customer_id": "customer123",
"setup_future_usage": "off_session"
}'
```
Response:
```
{
"payment_id": "pay_u8nPxFlL3ZUW94kkzrI1",
"merchant_id": "merchant_1725539597",
"status": "requires_payment_method",
"amount": 1650,
"net_amount": 1650,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB",
"created": "2024-09-17T12:59:17.770Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726577957,
"expires": 1726581557,
"secret": "epk_46a85e0e97b645a1bb2f838483b3bf70"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:14:17.769Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-17T12:59:17.902Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
2. Payments Confirm:
Request:
```
curl --location 'http://localhost:8080/payments/pay_u8nPxFlL3ZUW94kkzrI1/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data-raw '{
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87123456781234567890"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
"email": "something@example.com",
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_u8nPxFlL3ZUW94kkzrI1",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 1650,
"net_amount": 1650,
"amount_capturable": 1650,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB",
"created": "2024-09-17T12:59:17.770Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_K3jaclrwRSo2guy2kfn1",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_u8nPxFlL3ZUW94kkzrI1/merchant_1725539597/pay_u8nPxFlL3ZUW94kkzrI1_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:14:17.769Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_8qqABCQOMAznGanjmLhz",
"payment_method_status": null,
"updated": "2024-09-17T12:59:36.782Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
3. Creating payment using payment_method_id:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 179,
"currency": "EUR",
"confirm": true,
"customer_id": "customer123",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_8qqABCQOMAznGanjmLhz"
},
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_zeindrGrgMlzJscKZdAC",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 179,
"net_amount": 179,
"amount_capturable": 0,
"amount_received": 179,
"connector": "deutschebank",
"client_secret": "pay_zeindrGrgMlzJscKZdAC_secret_W4q8bNJWw2yH7MVaC70L",
"created": "2024-09-17T13:24:07.080Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "something@example.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": true,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something@example.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726579447,
"expires": 1726583047,
"secret": "epk_d80c49dcbeb1431cadf357b9c6d64ad9"
},
"manual_retry_allowed": false,
"connector_transaction_id": "nz17xcQ3x7q7kecPExgV0s",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-17T13:39:07.079Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_8qqABCQOMAznGanjmLhz",
"payment_method_status": "active",
"updated": "2024-09-17T13:24:08.282Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
| [
"crates/api_models/src/payments.rs",
"crates/hyperswitch_connectors/src/connectors/deutschebank.rs",
"crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs",
"crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs",
"crates/hyperswitch_connectors/src/connectors/novalnet/... | |
juspay/hyperswitch | juspay__hyperswitch-5906 | Bug: fix(user_roles): Profile level user_roles are not being updated
Currently, updating a profile level user role causes update user role API to break and throw error. This is because profile_id from the token is not being populated in the DB calls.
This makes the API unable to find the user role to be updated. | diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 868d2e65a24..d42f71695a5 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -119,7 +119,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- None,
+ user_from_token.profile_id.as_ref(),
UserRoleVersion::V2,
)
.await
@@ -165,7 +165,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- None,
+ user_from_token.profile_id.as_ref(),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id.clone(),
@@ -184,7 +184,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- None,
+ user_from_token.profile_id.as_ref(),
UserRoleVersion::V1,
)
.await
@@ -230,7 +230,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- None,
+ user_from_token.profile_id.as_ref(),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id,
| 2024-09-16T11:36:31Z |
## Description
<!-- Describe your changes in detail -->
Currently, profile level user_roles are not being updated. This PR fixes it.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #5906.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl 'http://localhost:8080/user/user/update_role' \
-H 'authorization: Bearer JWT' \
--data-raw '{"email":"email","role_id":"profile_iam_admin"}'
```
Response: 200 OK. | 90ebd54ec9dfabf03ee85c0d0e7d96755a135083 |
```
curl 'http://localhost:8080/user/user/update_role' \
-H 'authorization: Bearer JWT' \
--data-raw '{"email":"email","role_id":"profile_iam_admin"}'
```
Response: 200 OK.
| [
"crates/router/src/core/user_role.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5898 | Bug: feat(disputes): add support for disputes aggregate
1. Support for disputes aggregate
2. Support for disputes aggregate in profile level | diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs
index 5c2a2cc03d2..a1340b5aa5a 100644
--- a/crates/api_models/src/disputes.rs
+++ b/crates/api_models/src/disputes.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use masking::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
@@ -208,3 +210,9 @@ pub struct DeleteEvidenceRequest {
/// Evidence Type to be deleted
pub evidence_type: EvidenceType,
}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct DisputesAggregateResponse {
+ /// Different status of disputes with their count
+ pub status_with_count: HashMap<DisputeStatus, i64>,
+}
diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs
index 1ea6f4e8552..57f91330cc9 100644
--- a/crates/api_models/src/events/dispute.rs
+++ b/crates/api_models/src/events/dispute.rs
@@ -1,7 +1,8 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
use super::{
- DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest,
+ DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve,
+ DisputesAggregateResponse, SubmitEvidenceRequest,
};
impl ApiEventMetric for SubmitEvidenceRequest {
@@ -32,3 +33,9 @@ impl ApiEventMetric for DeleteEvidenceRequest {
})
}
}
+
+impl ApiEventMetric for DisputesAggregateResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::ResourceListAPI)
+ }
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 10c9dae2cc1..691b683aa3e 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1832,6 +1832,7 @@ pub enum DisputeStage {
serde::Serialize,
strum::Display,
strum::EnumString,
+ strum::EnumIter,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 8835f5f95a8..ff5936fc296 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -3,6 +3,9 @@ use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
use router_env::{instrument, tracing};
pub mod transformers;
+use std::collections::HashMap;
+
+use strum::IntoEnumIterator;
use super::{
errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt},
@@ -507,3 +510,31 @@ pub async fn delete_evidence(
})?;
Ok(services::ApplicationResponse::StatusOk)
}
+
+#[instrument(skip(state))]
+pub async fn get_aggregates_for_disputes(
+ state: SessionState,
+ merchant: domain::MerchantAccount,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: api::TimeRange,
+) -> RouterResponse<dispute_models::DisputesAggregateResponse> {
+ let db = state.store.as_ref();
+ let dispute_status_with_count = db
+ .get_dispute_status_with_count(merchant.get_id(), profile_id_list, &time_range)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to retrieve disputes aggregate")?;
+
+ let mut status_map: HashMap<storage_enums::DisputeStatus, i64> =
+ dispute_status_with_count.into_iter().collect();
+
+ for status in storage_enums::DisputeStatus::iter() {
+ status_map.entry(status).or_default();
+ }
+
+ Ok(services::ApplicationResponse::Json(
+ dispute_models::DisputesAggregateResponse {
+ status_with_count: status_map,
+ },
+ ))
+}
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index abe469dc32a..1d45cfd405f 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use error_stack::report;
use router_env::{instrument, tracing};
@@ -45,6 +47,13 @@ pub trait DisputeInterface {
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError>;
+
+ async fn get_dispute_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -126,6 +135,24 @@ impl DisputeInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ #[instrument(skip_all)]
+ async fn get_dispute_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Dispute::get_dispute_status_with_count(
+ &conn,
+ merchant_id,
+ profile_id_list,
+ time_range,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -358,6 +385,50 @@ impl DisputeInterface for MockDb {
Ok(dispute_to_update.clone())
}
+
+ async fn get_dispute_status_with_count(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
+ let locked_disputes = self.disputes.lock().await;
+
+ let filtered_disputes_data = locked_disputes
+ .iter()
+ .filter(|d| {
+ d.merchant_id == *merchant_id
+ && d.created_at >= time_range.start_time
+ && time_range
+ .end_time
+ .as_ref()
+ .map(|received_end_time| received_end_time >= &d.created_at)
+ .unwrap_or(true)
+ && profile_id_list
+ .as_ref()
+ .zip(d.profile_id.as_ref())
+ .map(|(received_profile_list, received_profile_id)| {
+ received_profile_list.contains(received_profile_id)
+ })
+ .unwrap_or(true)
+ })
+ .cloned()
+ .collect::<Vec<storage::Dispute>>();
+
+ Ok(filtered_disputes_data
+ .into_iter()
+ .fold(
+ HashMap::new(),
+ |mut acc: HashMap<common_enums::DisputeStatus, i64>, value| {
+ acc.entry(value.dispute_status)
+ .and_modify(|value| *value += 1)
+ .or_insert(1);
+ acc
+ },
+ )
+ .into_iter()
+ .collect::<Vec<(common_enums::DisputeStatus, i64)>>())
+ }
}
#[cfg(test)]
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 6c620c4fcdc..3a473891feb 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -629,6 +629,17 @@ impl DisputeInterface for KafkaStore {
.find_disputes_by_merchant_id_payment_id(merchant_id, payment_id)
.await
}
+
+ async fn get_dispute_status_with_count(
+ &self,
+ merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
+ self.diesel_store
+ .get_dispute_status_with_count(merchant_id, profile_id_list, time_range)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index da1a50b82ee..b0fd1091296 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1463,6 +1463,13 @@ impl Disputes {
web::resource("/accept/{dispute_id}")
.route(web::post().to(disputes::accept_dispute)),
)
+ .service(
+ web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)),
+ )
+ .service(
+ web::resource("/profile/aggregate")
+ .route(web::get().to(disputes::get_disputes_aggregate_profile)),
+ )
.service(
web::resource("/evidence")
.route(web::post().to(disputes::submit_dispute_evidence))
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 98ba33a64b4..5d8f7120f40 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -11,7 +11,7 @@ use super::app::AppState;
use crate::{
core::disputes,
services::{api, authentication as auth},
- types::api::disputes as dispute_types,
+ types::api::{disputes as dispute_types, payments::TimeRange},
};
/// Disputes - Retrieve Dispute
@@ -408,3 +408,68 @@ pub async fn delete_dispute_evidence(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
+pub async fn get_disputes_aggregate(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_param: web::Query<TimeRange>,
+) -> HttpResponse {
+ let flow = Flow::DisputesAggregate;
+ let query_param = query_param.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_param,
+ |state, auth, req, _| {
+ disputes::get_aggregates_for_disputes(state, auth.merchant_account, None, req)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))]
+pub async fn get_disputes_aggregate_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_param: web::Query<TimeRange>,
+) -> HttpResponse {
+ let flow = Flow::DisputesAggregate;
+ let query_param = query_param.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_param,
+ |state, auth, req, _| {
+ disputes::get_aggregates_for_disputes(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Profile,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index e63b00cd9bf..774e6c75bb4 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -175,6 +175,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::DisputesEvidenceSubmit
| Flow::AttachDisputeEvidence
| Flow::RetrieveDisputeEvidence
+ | Flow::DisputesAggregate
| Flow::DeleteDisputeEvidence => Self::Disputes,
Flow::CardsInfo => Self::CardsInfo,
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index 2728b29bc07..79b9a90343e 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -14,6 +14,13 @@ pub trait DisputeDbExt: Sized {
merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
+
+ async fn get_dispute_status_with_count(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
#[async_trait::async_trait]
@@ -72,4 +79,38 @@ impl DisputeDbExt for Dispute {
.change_context(errors::DatabaseError::NotFound)
.attach_printable_lazy(|| "Error filtering records by predicate")
}
+
+ async fn get_dispute_status_with_count(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
+ time_range: &api_models::payments::TimeRange,
+ ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
+ let mut query = <Self as HasTable>::table()
+ .group_by(dsl::dispute_status)
+ .select((dsl::dispute_status, diesel::dsl::count_star()))
+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .into_boxed();
+
+ if let Some(profile_id) = profile_id_list {
+ query = query.filter(dsl::profile_id.eq_any(profile_id));
+ }
+
+ query = query.filter(dsl::created_at.ge(time_range.start_time));
+
+ query = match time_range.end_time {
+ Some(ending_at) => query.filter(dsl::created_at.le(ending_at)),
+ None => query,
+ };
+
+ logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
+
+ db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
+ query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn),
+ db_metrics::DatabaseOperation::Count,
+ )
+ .await
+ .change_context(errors::DatabaseError::NotFound)
+ .attach_printable_lazy(|| "Error filtering records by predicate")
+ }
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index d815325a814..310f5ccecbf 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -290,6 +290,8 @@ pub enum Flow {
AttachDisputeEvidence,
/// Delete Dispute Evidence flow
DeleteDisputeEvidence,
+ /// Disputes aggregate flow
+ DisputesAggregate,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
| 2024-09-16T09:50:34Z |
## Description
<!-- Describe your changes in detail -->
- Add support for disputes aggregate
- Add support for profile level disputes aggregate
- For now it will have list of intent status along with the their count for a given time range.
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5898
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
**Dispute Aggregate**
Request:
```
curl --location 'http://localhost:8080/disputes/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response :
```
{
"status_with_count": {
"dispute_cancelled": 0,
"dispute_expired": 3,
"dispute_lost": 2,
"dispute_opened": 0,
"dispute_accepted": 0,
"dispute_challenged": 0,
"dispute_won": 0
}
}
```
**Profile level Dispute aggregate**
Request
```
curl --location 'http://localhost:8080/disputes/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"status_with_count": {
"dispute_lost": 2,
"dispute_accepted": 0,
"dispute_opened": 0,
"dispute_challenged": 0,
"dispute_expired": 3,
"dispute_cancelled": 0,
"dispute_won": 0
}
}
``` | 90ebd54ec9dfabf03ee85c0d0e7d96755a135083 |
**Dispute Aggregate**
Request:
```
curl --location 'http://localhost:8080/disputes/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response :
```
{
"status_with_count": {
"dispute_cancelled": 0,
"dispute_expired": 3,
"dispute_lost": 2,
"dispute_opened": 0,
"dispute_accepted": 0,
"dispute_challenged": 0,
"dispute_won": 0
}
}
```
**Profile level Dispute aggregate**
Request
```
curl --location 'http://localhost:8080/disputes/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT' \
--data ''
```
Response
```
{
"status_with_count": {
"dispute_lost": 2,
"dispute_accepted": 0,
"dispute_opened": 0,
"dispute_challenged": 0,
"dispute_expired": 3,
"dispute_cancelled": 0,
"dispute_won": 0
}
}
```
| [
"crates/api_models/src/disputes.rs",
"crates/api_models/src/events/dispute.rs",
"crates/common_enums/src/enums.rs",
"crates/router/src/core/disputes.rs",
"crates/router/src/db/dispute.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/disputes.rs",... | |
juspay/hyperswitch | juspay__hyperswitch-5888 | Bug: [BUG] remove redundant DB calls when FRM feature is not enabled
### Bug Description
FRM is a payment feature which is integrated in HyperSwitch behind `frm` feature flag. There are some DB queries (which are generally not behind a feature flag) which are being executed even when `frm` feature is disabled.
### Expected Behavior
Underlying DB queries should be executed only when the feature which requires it is enabled. In this case, FRM DB queries should be executed only when `frm` is enabled
### Actual Behavior
FRM DB queries are being executed regardless of `frm` feature flag
### Steps To Reproduce
---
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 38cf72a3e2f..9c5b632eff0 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -136,13 +136,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
- let frm_response = db
- .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
- .attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id().get_string_repr())
- });
+ let frm_response = if cfg!(feature = "frm") {
+ db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .attach_printable_lazy(|| {
+ format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id().get_string_repr())
+ })
+ .ok()
+ } else {
+ None
+ };
let payment_data = PaymentData {
flow: PhantomData,
@@ -180,7 +184,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
- frm_message: frm_response.ok(),
+ frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 570337a5555..3d67dadd34d 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -117,13 +117,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
- let frm_response = db
- .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
- .attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id())
- });
+ let frm_response = if cfg!(feature = "frm") {
+ db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .attach_printable_lazy(|| {
+ format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id())
+ })
+ .ok()
+ } else {
+ None
+ };
let profile_id = payment_intent
.profile_id
@@ -176,7 +180,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
- frm_message: frm_response.ok(),
+ frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index d7ca01e6661..0508d0549e8 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -348,13 +348,17 @@ async fn get_tracker_for_sync<
format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id())
})?;
- let frm_response = db
- .find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone())
- .await
- .change_context(errors::ApiErrorResponse::PaymentNotFound)
- .attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id())
- });
+ let frm_response = if cfg!(feature = "frm") {
+ db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone())
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentNotFound)
+ .attach_printable_lazy(|| {
+ format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id())
+ })
+ .ok()
+ } else {
+ None
+ };
let contains_encoded_data = payment_attempt.encoded_data.is_some();
@@ -472,7 +476,7 @@ async fn get_tracker_for_sync<
redirect_response: None,
payment_link_data: None,
surcharge_details: None,
- frm_message: frm_response.ok(),
+ frm_message: frm_response,
incremental_authorization_details: None,
authorizations,
authentication,
| 2024-09-16T04:11:58Z |
## Description
Described in #5888
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Ensures FRM DB queries are not executed if `frm` feature flag is not enabled. There are a couple of features disabled in HS production, and the DB migrations for such features have not been executed. This leads to unnecessary missing column logs in production - `ERROR: column fraud_check.last_step does not exist at character 443`
Moving such DB queries behind the feature flag ensures they are not executed in the flow.
## How did you test it?
<details>
<summary>1. Create a txn</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_4cUeectovRvg0seB0AhDXZ04342m045JeKncgz5XfwkkhJujY4gy7TzfTS9uvdiP' \
--data-raw '{
"amount": 10000,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
Response
{
"payment_id": "pay_vOR4HKlsgkvHTnZf4PjC",
"merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"created": "2024-09-16T04:20:41.261Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1726460441,
"expires": 1726464041,
"secret": "epk_51ac152969e5409fa03e13c462de5474"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_RSxpgp1DT0ak3TCybfa5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-16T04:35:41.261Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-16T04:20:41.283Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
</details>
<details>
<summary>2. Confirm the txn</summary>
cURL
curl --location 'http://localhost:8080/payments/pay_vOR4HKlsgkvHTnZf4PjC/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_8e7e083168464148bdc4aa4e18eb12ac' \
--data-raw '{
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"payment_method": "bank_debit",
"payment_method_type": "ach",
"payment_method_data": {
"bank_debit": {
"ach_bank_debit": {
"account_number": "40308669",
"routing_number": "121000358",
"sort_code": "560036",
"shopper_email": "example@gmail.com",
"card_holder_name": "joseph Doe",
"bank_name": "wells_fargo",
"bank_account_holder_name": "David Archer",
"billing_details": {
"houseNumberOrName": "50",
"street": "Test Street",
"city": "Amsterdam",
"stateOrProvince": "NY",
"postalCode": "12010",
"country": "US",
"name": "A. Klaassen",
"email": "example@gmail.com"
},
"reference": "daslvcgbaieh"
}
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_vOR4HKlsgkvHTnZf4PjC",
"merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "adyen",
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"created": "2024-09-16T04:20:41.261Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"ach": {
"account_number": "****8669",
"routing_number": "121***358",
"card_holder_name": "joseph Doe",
"bank_account_holder_name": "David Archer",
"bank_name": "wells_fargo",
"bank_type": null,
"bank_holder_type": null
}
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "ach",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "WMVPLJG2ZG47JFV5",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_vOR4HKlsgkvHTnZf4PjC_1",
"payment_link": null,
"profile_id": "pro_RSxpgp1DT0ak3TCybfa5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_dQv2PlaakvcRdJ4XR04T",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-16T04:35:41.261Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-16T04:20:44.432Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
</details>
<details>
<summary>3. Look at the logs to see if fraud_check queries are present (should be present when `frm` is enabled and absent when `frm` feature is disabled. </summary>

</details> | 2aa215440e0531e315e61ee30bbbc5a5685481b3 | <details>
<summary>1. Create a txn</summary>
cURL
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_4cUeectovRvg0seB0AhDXZ04342m045JeKncgz5XfwkkhJujY4gy7TzfTS9uvdiP' \
--data-raw '{
"amount": 10000,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
Response
{
"payment_id": "pay_vOR4HKlsgkvHTnZf4PjC",
"merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be",
"status": "requires_payment_method",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"created": "2024-09-16T04:20:41.261Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1726460441,
"expires": 1726464041,
"secret": "epk_51ac152969e5409fa03e13c462de5474"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_RSxpgp1DT0ak3TCybfa5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-16T04:35:41.261Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-16T04:20:41.283Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
</details>
<details>
<summary>2. Confirm the txn</summary>
cURL
curl --location 'http://localhost:8080/payments/pay_vOR4HKlsgkvHTnZf4PjC/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_8e7e083168464148bdc4aa4e18eb12ac' \
--data-raw '{
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"payment_method": "bank_debit",
"payment_method_type": "ach",
"payment_method_data": {
"bank_debit": {
"ach_bank_debit": {
"account_number": "40308669",
"routing_number": "121000358",
"sort_code": "560036",
"shopper_email": "example@gmail.com",
"card_holder_name": "joseph Doe",
"bank_name": "wells_fargo",
"bank_account_holder_name": "David Archer",
"billing_details": {
"houseNumberOrName": "50",
"street": "Test Street",
"city": "Amsterdam",
"stateOrProvince": "NY",
"postalCode": "12010",
"country": "US",
"name": "A. Klaassen",
"email": "example@gmail.com"
},
"reference": "daslvcgbaieh"
}
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
}
}'
Response
{
"payment_id": "pay_vOR4HKlsgkvHTnZf4PjC",
"merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "adyen",
"client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD",
"created": "2024-09-16T04:20:41.261Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"ach": {
"account_number": "****8669",
"routing_number": "121***358",
"card_holder_name": "joseph Doe",
"bank_account_holder_name": "David Archer",
"bank_name": "wells_fargo",
"bank_type": null,
"bank_holder_type": null
}
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "ach",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "WMVPLJG2ZG47JFV5",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_vOR4HKlsgkvHTnZf4PjC_1",
"payment_link": null,
"profile_id": "pro_RSxpgp1DT0ak3TCybfa5",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_dQv2PlaakvcRdJ4XR04T",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-16T04:35:41.261Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-16T04:20:44.432Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
</details>
<details>
<summary>3. Look at the logs to see if fraud_check queries are present (should be present when `frm` is enabled and absent when `frm` feature is disabled. </summary>

</details>
| [
"crates/router/src/core/payments/operations/payment_approve.rs",
"crates/router/src/core/payments/operations/payment_reject.rs",
"crates/router/src/core/payments/operations/payment_status.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5886 | Bug: [FEATURE] Add Cell ID in config
### Feature Description
Add global cell id information in config for v2
### Possible Implementation
Will need to add in settings
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/config/config.example.toml b/config/config.example.toml
index 1f32481fec7..cf6703f43d4 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -734,6 +734,9 @@ connector_list = ""
[recipient_emails]
recon = "test@example.com"
+[cell_information]
+id = "12345" # Default CellID for Global Cell Information
+
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard" # Supported card networks for network tokenization
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 319cdafed1d..db43cac979b 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -302,6 +302,9 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p
[user_auth_methods]
encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table
+[cell_information]
+id = "12345" # Default CellID for Global Cell Information
+
[network_tokenization_service] # Network Tokenization Service Configuration
generate_token_url= "" # base url to generate token
fetch_token_url= "" # base url to fetch token
diff --git a/config/development.toml b/config/development.toml
index 6e56d5bb14d..29beed992f6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -735,6 +735,9 @@ encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC69
[locker_based_open_banking_connectors]
connector_list = ""
+[cell_information]
+id = "12345"
+
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 15038da0125..77a735aa757 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -137,8 +137,8 @@ ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox"
fiuu.base_url = "https://sandbox.merchant.razer.com/"
-fiuu.secondary_base_url="https://sandbox.merchant.razer.com/"
-fiuu.third_base_url="https://api.merchant.razer.com/"
+fiuu.secondary_base_url = "https://sandbox.merchant.razer.com/"
+fiuu.third_base_url = "https://api.merchant.razer.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
globepay.base_url = "https://pay.globepay.co/"
@@ -380,7 +380,7 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M
upi_collect = { country = "IN", currency = "INR" }
[pm_filters.plaid]
-open_banking_pis = {currency = "EUR,GBP"}
+open_banking_pis = { currency = "EUR,GBP" }
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -552,7 +552,7 @@ sdk_eligible_payment_methods = "card"
[multitenancy]
enabled = false
-global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
+global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
[multitenancy.tenants]
public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
@@ -592,6 +592,9 @@ ach = { country = "US", currency = "USD" }
[locker_based_open_banking_connectors]
connector_list = ""
+[cell_information]
+id = "12345"
+
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs
index 5ed23a177b6..c0b6384abc6 100644
--- a/crates/common_utils/src/id_type/global_id.rs
+++ b/crates/common_utils/src/id_type/global_id.rs
@@ -63,27 +63,29 @@ impl From<AlphaNumericIdError> for CellIdError {
impl CellId {
/// Create a new cell id from a string
- fn from_str(cell_id_string: &str) -> Result<Self, CellIdError> {
- let trimmed_input_string = cell_id_string.trim().to_string();
+ pub fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> {
+ let trimmed_input_string = cell_id_string.as_ref().trim().to_string();
let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
- pub fn from_string(input_string: String) -> error_stack::Result<Self, errors::ValidationError> {
- Self::from_str(&input_string).change_context(
- errors::ValidationError::IncorrectValueProvided {
- field_name: "cell_id",
- },
- )
- }
-
/// Get the string representation of the cell id
fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
+impl<'de> serde::Deserialize<'de> for CellId {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ let deserialized_string = String::deserialize(deserializer)?;
+ Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom)
+ }
+}
+
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum GlobalIdError {
diff --git a/crates/common_utils/src/id_type/global_id/payment_methods.rs b/crates/common_utils/src/id_type/global_id/payment_methods.rs
index 5ccb774f6ea..3929efd09b5 100644
--- a/crates/common_utils/src/id_type/global_id/payment_methods.rs
+++ b/crates/common_utils/src/id_type/global_id/payment_methods.rs
@@ -28,8 +28,10 @@ pub enum GlobalPaymentMethodIdError {
impl GlobalPaymentMethodId {
/// Create a new GlobalPaymentMethodId from celll id information
- pub fn generate(cell_id: &str) -> error_stack::Result<Self, errors::ValidationError> {
- let cell_id = CellId::from_string(cell_id.to_string())?;
+ pub fn generate(cell_id: &str) -> error_stack::Result<Self, GlobalPaymentMethodIdError> {
+ let cell_id = CellId::from_str(cell_id)
+ .change_context(GlobalPaymentMethodIdError::ConstructionError)
+ .attach_printable("Failed to construct CellId from str")?;
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
Ok(Self(global_id))
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 442561c2ca3..83d159f6d29 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -33,7 +33,7 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors
payout_retry = ["payouts"]
recon = ["email", "api_models/recon"]
retry = []
-v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2"]
+v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2"]
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"]
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 8c893b88319..e1b68efc446 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -498,6 +498,8 @@ pub(crate) async fn fetch_raw_secrets(
decision: conf.decision,
locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
grpc_client: conf.grpc_client,
+ #[cfg(feature = "v2")]
+ cell_information: conf.cell_information,
network_tokenization_supported_card_networks: conf
.network_tokenization_supported_card_networks,
network_tokenization_service,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 675b8c44e2a..0a7defc4063 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -122,6 +122,8 @@ pub struct Settings<S: SecretState> {
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
pub grpc_client: GrpcClientSettings,
+ #[cfg(feature = "v2")]
+ pub cell_information: CellInformation,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
@@ -854,6 +856,8 @@ impl Settings<SecuredSecret> {
self.generic_link.payment_method_collect.validate()?;
self.generic_link.payout_link.validate()?;
+ #[cfg(feature = "v2")]
+ self.cell_information.validate()?;
self.network_tokenization_service
.as_ref()
.map(|x| x.get_inner().validate())
@@ -940,6 +944,26 @@ pub struct ServerTls {
pub certificate: PathBuf,
}
+#[cfg(feature = "v2")]
+#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
+pub struct CellInformation {
+ pub id: common_utils::id_type::CellId,
+}
+
+#[cfg(feature = "v2")]
+impl Default for CellInformation {
+ fn default() -> Self {
+ // We provide a static default cell id for constructing application settings.
+ // This will only panic at application startup if we're unable to construct the default,
+ // around the time of deserializing application settings.
+ // And a panic at application startup is considered acceptable.
+ #[allow(clippy::expect_used)]
+ let cell_id = common_utils::id_type::CellId::from_str("defid")
+ .expect("Failed to create a default for Cell Id");
+ Self { id: cell_id }
+ }
+}
+
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 67db7b1266c..7736d7b3f37 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -193,6 +193,19 @@ impl super::settings::GenericLinkEnvConfig {
}
}
+#[cfg(feature = "v2")]
+impl super::settings::CellInformation {
+ pub fn validate(&self) -> Result<(), ApplicationError> {
+ use common_utils::{fp_utils::when, id_type};
+
+ when(self == &super::settings::CellInformation::default(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "CellId cannot be set to a default".into(),
+ ))
+ })
+ }
+}
+
impl super::settings::NetworkTokenizationService {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
| 2024-09-13T15:00:31Z |
## Description
<!-- Describe your changes in detail -->
Added Cell Id in SessionState config
The strategy is use check the value of Cell id at application start and panic if it equals the default value.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cannot be tested, as setting the cell id as default in config will cause the application to panic. | c0cac8d9135b14945ce5763327ec16b1578ca2a2 |
Cannot be tested, as setting the cell id as default in config will cause the application to panic.
| [
"config/config.example.toml",
"config/deployments/env_specific.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/common_utils/src/id_type/global_id.rs",
"crates/common_utils/src/id_type/global_id/payment_methods.rs",
"crates/router/Cargo.toml",
"crates/router/src/configs/secrets_... | |
juspay/hyperswitch | juspay__hyperswitch-5891 | Bug: [FEATURE] Open banking SDK fixes
### Feature Description
SDK would send headers in order to identify the client platform, we need to consume in the backend and process accordingly.
### Possible Implementation
Need to consume headers in specific flows.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 20f1205e14b..c50b1fb1d05 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -793,6 +793,8 @@ pub struct HeaderPayload {
pub x_client_platform: Option<api_enums::ClientPlatform>,
pub x_merchant_domain: Option<String>,
pub locale: Option<String>,
+ pub x_app_id: Option<String>,
+ pub x_redirect_uri: Option<String>,
}
impl HeaderPayload {
diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs
index 8ed52907da8..443a4c30394 100644
--- a/crates/api_models/src/pm_auth.rs
+++ b/crates/api_models/src/pm_auth.rs
@@ -4,6 +4,8 @@ use common_utils::{
id_type, impl_api_event_type,
};
+use crate::enums as api_enums;
+
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct LinkTokenCreateRequest {
@@ -12,6 +14,9 @@ pub struct LinkTokenCreateRequest {
pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch
pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector
pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector
+ pub client_platform: api_enums::ClientPlatform, // Client Platform to perform platform based processing
+ pub android_package_name: Option<String>, // Android Package name to be sent for Android platform
+ pub redirect_uri: Option<String>, // Merchant redirect_uri to be sent in case of IOS platform
}
#[derive(Debug, Clone, serde::Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 653275bd560..9136ee35c7d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2479,6 +2479,7 @@ pub enum ClientPlatform {
#[default]
Web,
Ios,
+ Android,
#[serde(other)]
Unknown,
}
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index df0b63833d9..dde38561b44 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -80,6 +80,10 @@ pub struct RouterData<Flow, Request, Response> {
pub minor_amount_captured: Option<MinorUnit>,
pub integrity_check: Result<(), IntegrityCheckError>,
+
+ pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>,
+
+ pub header_payload: Option<api_models::payments::HeaderPayload>,
}
// Different patterns of authentication.
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index ec182056f6c..93ace230f19 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -346,6 +346,8 @@ pub struct PaymentsPostProcessingData {
pub customer_id: Option<id_type::CustomerId>,
pub connector_transaction_id: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
+ pub connector_meta_data: Option<pii::SecretSerdeValue>,
+ pub header_payload: Option<api_models::payments::HeaderPayload>,
}
impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
@@ -371,6 +373,8 @@ impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsRes
.get_payment_billing()
.and_then(|bl| bl.address.as_ref())
.and_then(|address| address.country),
+ connector_meta_data: data.connector_meta_data.clone(),
+ header_payload: data.header_payload,
})
}
}
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
index 109cc5a5c15..af0c26a5b85 100644
--- a/crates/pm_auth/src/connector/plaid/transformers.rs
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -15,6 +15,8 @@ pub struct PlaidLinkTokenRequest {
language: String,
products: Vec<String>,
user: User,
+ android_package_name: Option<String>,
+ redirect_uri: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
@@ -42,6 +44,30 @@ impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
},
)?,
},
+ android_package_name: match item.request.client_platform {
+ api_models::enums::ClientPlatform::Android => {
+ Some(item.request.android_package_name.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "android_package_name",
+ },
+ )?)
+ }
+ api_models::enums::ClientPlatform::Ios
+ | api_models::enums::ClientPlatform::Web
+ | api_models::enums::ClientPlatform::Unknown => None,
+ },
+ redirect_uri: match item.request.client_platform {
+ api_models::enums::ClientPlatform::Ios => {
+ Some(item.request.redirect_uri.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "redirect_uri",
+ },
+ )?)
+ }
+ api_models::enums::ClientPlatform::Android
+ | api_models::enums::ClientPlatform::Web
+ | api_models::enums::ClientPlatform::Unknown => None,
+ },
})
}
}
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index 4c20e879d8b..878043afe50 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -3,6 +3,7 @@ pub mod api;
use std::marker::PhantomData;
use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate};
+use api_models::enums as api_enums;
use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types};
use masking::Secret;
@@ -24,6 +25,9 @@ pub struct LinkTokenRequest {
pub country_codes: Option<Vec<String>>,
pub language: Option<String>,
pub user_info: Option<id_type::CustomerId>,
+ pub client_platform: api_enums::ClientPlatform,
+ pub android_package_name: Option<String>,
+ pub redirect_uri: Option<String>,
}
#[derive(Debug, Clone)]
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs
index cf9c91afd0c..c4eb5a7a035 100644
--- a/crates/router/src/connector/plaid/transformers.rs
+++ b/crates/router/src/connector/plaid/transformers.rs
@@ -1,6 +1,5 @@
use common_enums::Currency;
use common_utils::types::FloatMajorUnit;
-use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -73,6 +72,8 @@ pub struct PlaidLinkTokenRequest {
products: Vec<String>,
user: User,
payment_initiation: PlaidPaymentInitiation,
+ redirect_uri: Option<String>,
+ android_package_name: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
@@ -105,21 +106,21 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "payment_id",
})?;
- let recipient_val = item
+ let recipient_type = item
.router_data
- .connector_meta_data
+ .additional_merchant_data
.as_ref()
+ .map(|merchant_data| match merchant_data {
+ api_models::admin::AdditionalMerchantData::OpenBankingRecipientData(
+ data,
+ ) => data.clone(),
+ })
.ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "connector_customer",
- })?
- .peek()
- .clone();
-
- let recipient_type =
- serde_json::from_value::<types::MerchantRecipientData>(recipient_val)
- .change_context(errors::ConnectorError::ParsingFailed)?;
+ field_name: "additional_merchant_data",
+ })?;
+
let recipient_id = match recipient_type {
- types::MerchantRecipientData::ConnectorRecipientId(id) => {
+ api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => {
Ok(id.peek().to_string())
}
_ => Err(errors::ConnectorError::MissingRequiredField {
@@ -159,35 +160,73 @@ impl TryFrom<&types::PaymentsSyncRouterData> for PlaidSyncRequest {
impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> {
- match item.request.payment_method_data.clone() {
+ match item.request.payment_method_data {
domain::PaymentMethodData::OpenBanking(ref data) => match data {
- domain::OpenBankingData::OpenBankingPIS { .. } => Ok(Self {
- client_name: "Hyperswitch".to_string(),
- country_codes: item
- .request
- .country
- .map(|code| vec![code.to_string()])
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "billing.address.country",
- })?,
- language: "en".to_string(),
- products: vec!["payment_initiation".to_string()],
- user: User {
- client_user_id: item
- .request
- .customer_id
- .clone()
- .map(|id| id.get_string_repr().to_string())
- .unwrap_or("default cust".to_string()),
- },
- payment_initiation: PlaidPaymentInitiation {
- payment_id: item
+ domain::OpenBankingData::OpenBankingPIS { .. } => {
+ let headers = item.header_payload.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "header_payload",
+ },
+ )?;
+
+ let platform = headers.x_client_platform.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "x_client_platform",
+ },
+ )?;
+
+ let (is_android, is_ios) = match platform {
+ common_enums::ClientPlatform::Android => (true, false),
+ common_enums::ClientPlatform::Ios => (false, true),
+ _ => (false, false),
+ };
+
+ Ok(Self {
+ client_name: "Hyperswitch".to_string(),
+ country_codes: item
.request
- .connector_transaction_id
- .clone()
- .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
- },
- }),
+ .country
+ .map(|code| vec![code.to_string()])
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "billing.address.country",
+ })?,
+ language: "en".to_string(),
+ products: vec!["payment_initiation".to_string()],
+ user: User {
+ client_user_id: item
+ .request
+ .customer_id
+ .clone()
+ .map(|id| id.get_string_repr().to_string())
+ .unwrap_or("default cust".to_string()),
+ },
+ payment_initiation: PlaidPaymentInitiation {
+ payment_id: item
+ .request
+ .connector_transaction_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
+ },
+ android_package_name: if is_android {
+ Some(headers.x_app_id.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "x-app-id",
+ },
+ )?)
+ } else {
+ None
+ },
+ redirect_uri: if is_ios {
+ Some(headers.x_redirect_uri.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "x_redirect_uri",
+ },
+ )?)
+ } else {
+ None
+ },
+ })
+ }
},
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index f77296d7bc1..5b512bdd2b6 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -61,8 +61,12 @@ pub async fn perform_authentication(
webhook_url,
three_ds_requestor_url,
)?;
- let response =
- utils::do_auth_connector_call(state, authentication_connector.clone(), router_data).await?;
+ let response = Box::pin(utils::do_auth_connector_call(
+ state,
+ authentication_connector.clone(),
+ router_data,
+ ))
+ .await?;
let authentication =
utils::update_trackers(state, response.clone(), authentication_data, None).await?;
response
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 4a1298bb7bf..bbbbf9a2514 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -182,6 +182,8 @@ pub fn construct_router_data<F: Clone, Req, Res>(
payment_method_status: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
})
}
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 90c36ba9aa8..72a75661984 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -93,6 +93,7 @@ where
customer,
&merchant_connector_account,
None,
+ None,
)
.await?;
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 74606eb5917..92dc2a99e8a 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -39,6 +39,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
_customer: &Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
todo!()
@@ -54,6 +55,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
@@ -151,6 +153,8 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index f3eab2dd8d1..5ca790d4813 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -108,6 +108,8 @@ pub async fn construct_fulfillment_router_data<'a>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index 6603f09cad3..e4d002931ec 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -36,6 +36,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
_customer: &Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
todo!()
@@ -51,6 +52,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
@@ -120,6 +122,8 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index 70006f555fe..56f6545cfd7 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
_customer: &Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
todo!()
}
@@ -48,6 +49,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
let status = storage_enums::AttemptStatus::Pending;
@@ -128,6 +130,8 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
};
Ok(router_data)
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index ad62541155f..ebd967e7515 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -39,6 +39,7 @@ impl
_customer: &Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
@@ -55,6 +56,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
@@ -134,6 +136,8 @@ impl
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload,
};
Ok(router_data)
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index de4b0b77feb..544f9ea756e 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -78,6 +78,8 @@ pub async fn construct_mandate_revoke_router_data(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0ec14bd69ed..420757048f7 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -374,6 +374,7 @@ where
&connector,
&mut payment_data,
op_ref,
+ Some(header_payload.clone()),
)
.await?;
}
@@ -498,6 +499,7 @@ where
&connector_data,
&mut payment_data,
op_ref,
+ Some(header_payload.clone()),
)
.await?;
}
@@ -1625,6 +1627,7 @@ where
customer,
&merchant_connector_account,
merchant_recipient_data,
+ None,
)
.await?;
@@ -1958,6 +1961,7 @@ where
customer,
&merchant_connector_account,
None,
+ None,
)
.await?;
@@ -2103,6 +2107,7 @@ where
customer,
merchant_connector_account,
None,
+ None,
)
.await?;
@@ -2287,6 +2292,7 @@ async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>(
connector: &api::ConnectorData,
payment_data: &mut D,
_operation: &BoxedOperation<'_, F, Q, D>,
+ header_payload: Option<HeaderPayload>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
@@ -2307,6 +2313,7 @@ where
customer,
merchant_conn_account,
None,
+ header_payload,
)
.await?;
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 1dec8911d31..e82af808b55 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -38,6 +38,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, Req, Res>>;
#[cfg(all(feature = "v2", feature = "customer_v2"))]
@@ -50,6 +51,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {
_customer: &Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, Req, Res>>;
async fn get_merchant_recipient_data<'a>(
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index e425abce336..aba38a40cb2 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -25,6 +25,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
@@ -38,6 +39,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 0a55cefb427..ca01f377de7 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -37,6 +37,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::Authorize,
@@ -56,6 +57,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index a56c49611a6..144bea32592 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Void,
@@ -38,6 +39,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index cb37a75813b..196466d208d 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -25,6 +25,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Capture,
@@ -38,6 +39,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
index 212fb4bc240..1335e44b660 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -29,6 +29,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
@@ -48,6 +49,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
index 226852e4a3c..76141537351 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -28,6 +28,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::IncrementalAuthorization,
@@ -41,6 +42,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index 428d170633e..ac205bcb7c8 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -26,6 +26,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
@@ -41,6 +42,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index d2e65c8a638..f66bdfe3dfd 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -24,6 +24,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsRejectRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Reject,
@@ -37,6 +38,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 54d8dc230c7..c4037a1a5b6 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -40,6 +40,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
@@ -53,6 +54,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs
index c12667e19a2..682c20b725d 100644
--- a/crates/router/src/core/payments/flows/session_update_flow.rs
+++ b/crates/router/src/core/payments/flows/session_update_flow.rs
@@ -28,6 +28,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
Box::pin(
transformers::construct_router_data_to_update_calculated_tax::<
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index c412fd2b37f..293371024c9 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -32,6 +32,7 @@ impl
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::SetupMandate,
@@ -45,6 +46,7 @@ impl
customer,
merchant_connector_account,
merchant_recipient_data,
+ header_payload,
))
.await
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 2af3c52d758..9be4b02cbbd 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3634,6 +3634,8 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
connector_response: router_data.connector_response,
integrity_check: Ok(()),
connector_wallets_details: router_data.connector_wallets_details,
+ additional_merchant_data: router_data.additional_merchant_data,
+ header_payload: router_data.header_payload,
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 93fa3ed44b8..de48f7e700a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -151,6 +151,8 @@ where
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -167,6 +169,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
_customer: &'a Option<domain::Customer>,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
+ _header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -190,6 +193,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
+ header_payload: Option<api_models::payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -318,14 +322,7 @@ where
.payment_attempt
.authentication_type
.unwrap_or_default(),
- connector_meta_data: if let Some(data) = merchant_recipient_data {
- let val = serde_json::to_value(data)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while encoding MerchantRecipientData")?;
- Some(Secret::new(val))
- } else {
- merchant_connector_account.get_metadata()
- },
+ connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
request: T::try_from(additional_data)?,
response,
@@ -364,6 +361,12 @@ where
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: merchant_recipient_data.map(|data| {
+ api_models::admin::AdditionalMerchantData::foreign_from(
+ types::AdditionalMerchantData::OpenBankingRecipientData(data),
+ )
+ }),
+ header_payload,
};
Ok(router_data)
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 85d5b78521f..6c8ad32234c 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -717,13 +717,13 @@ pub async fn payouts_fulfill_core(
.await?
.get_required_value("payout_method_data")?,
);
- fulfill_payout(
+ Box::pin(fulfill_payout(
&state,
&merchant_account,
&key_store,
&connector_data,
&mut payout_data,
- )
+ ))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
@@ -1121,13 +1121,13 @@ pub async fn call_connector_payout(
// Auto fulfillment flow
let status = payout_data.payout_attempt.status;
if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {
- fulfill_payout(
+ Box::pin(fulfill_payout(
state,
merchant_account,
key_store,
connector_data,
payout_data,
- )
+ ))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
}
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index f948d7faaf9..78b06a421af 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -165,6 +165,9 @@ pub async fn create_link_token(
)?]),
language: payload.language,
user_info: payment_intent.and_then(|pi| pi.customer_id),
+ client_platform: payload.client_platform,
+ android_package_name: payload.android_package_name,
+ redirect_uri: payload.redirect_uri,
},
response: Ok(pm_auth_types::LinkTokenResponse {
link_token: "".to_string(),
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 0f7abf44b14..a45b3be8a3c 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -1185,7 +1185,7 @@ pub async fn schedule_refund_execution(
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
- let update_refund = trigger_refund_to_gateway(
+ let update_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_account,
@@ -1194,7 +1194,7 @@ pub async fn schedule_refund_execution(
payment_intent,
creds_identifier,
charges,
- )
+ ))
.await;
match update_refund {
@@ -1438,7 +1438,7 @@ pub async fn trigger_refund_execute_workflow(
};
//trigger refund request to gateway
- let updated_refund = trigger_refund_to_gateway(
+ let updated_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
&merchant_account,
@@ -1447,7 +1447,7 @@ pub async fn trigger_refund_execute_workflow(
&payment_intent,
None,
charges,
- )
+ ))
.await?;
add_refund_sync_task(
db,
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 0e8b21f3a8a..8e86fb86967 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -215,6 +215,8 @@ pub async fn construct_payout_router_data<'a, F>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
@@ -370,6 +372,8 @@ pub async fn construct_refund_router_data<'a, F>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
@@ -677,6 +681,8 @@ pub async fn construct_accept_dispute_router_data<'a>(
refund_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -769,6 +775,8 @@ pub async fn construct_submit_evidence_router_data<'a>(
dispute_id: Some(dispute.dispute_id.clone()),
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -867,6 +875,8 @@ pub async fn construct_upload_file_router_data<'a>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -974,6 +984,8 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone
payment_method_status: None,
minor_amount_captured: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -1069,6 +1081,8 @@ pub async fn construct_defend_dispute_router_data<'a>(
dispute_id: Some(dispute.dispute_id.clone()),
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
@@ -1159,6 +1173,8 @@ pub async fn construct_retrieve_file_router_data<'a>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 8987a9384df..8680e43eff3 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -120,6 +120,8 @@ pub async fn construct_webhook_router_data<'a>(
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
};
Ok(router_data)
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index caa96826937..b18c9ff4e80 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -83,6 +83,8 @@ pub mod headers {
pub const BROWSER_NAME: &str = "x-browser-name";
pub const X_CLIENT_PLATFORM: &str = "x-client-platform";
pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain";
+ pub const X_APP_ID: &str = "x-app-id";
+ pub const X_REDIRECT_URI: &str = "x-redirect-uri";
pub const X_TENANT_ID: &str = "x-tenant-id";
}
diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs
index f1aec19bd30..22930916093 100644
--- a/crates/router/src/services/conversion_impls.rs
+++ b/crates/router/src/services/conversion_impls.rs
@@ -74,6 +74,8 @@ fn get_default_router_data<F, Req, Resp>(
payment_method_status: None,
minor_amount_captured: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 16a8ed1ccc4..27fa1e1ced0 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -906,6 +906,8 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
+ additional_merchant_data: data.additional_merchant_data.clone(),
+ header_payload: data.header_payload.clone(),
}
}
}
@@ -968,6 +970,8 @@ impl<F1, F2>
dispute_id: None,
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
+ additional_merchant_data: data.additional_merchant_data.clone(),
+ header_payload: data.header_payload.clone(),
}
}
}
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 1b3162a3549..6c92b1b801a 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -113,6 +113,8 @@ impl VerifyConnectorData {
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
}
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 46210d4dd09..3df2299a2ae 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -21,8 +21,8 @@ use super::domain;
use crate::{
core::errors,
headers::{
- ACCEPT_LANGUAGE, BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION,
- X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE,
+ ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE,
+ X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI,
},
services::authentication::get_header_value_by_key,
types::{
@@ -1420,6 +1420,12 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload {
let x_merchant_domain =
get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string());
+ let x_app_id =
+ get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string());
+
+ let x_redirect_uri =
+ get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string());
+
Ok(Self {
payment_confirm_source,
client_source,
@@ -1429,6 +1435,8 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload {
x_client_platform,
x_merchant_domain,
locale,
+ x_app_id,
+ x_redirect_uri,
})
}
}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index f3ff1a60361..5d48a0188ff 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -126,6 +126,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
refund_id: None,
dispute_id: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
}
}
@@ -193,6 +195,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
refund_id: None,
dispute_id: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
}
}
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index ea12d463fbd..582c212c241 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -544,6 +544,8 @@ pub trait ConnectorActions: Connector {
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
+ additional_merchant_data: None,
+ header_payload: None,
}
}
| 2024-09-13T13:40:37Z |
## Description
<!-- Describe your changes in detail -->
- Refactored RouterData to use HeaderPayload for Android/IOS Platform specific flows.
- Refactored Open banking flows to consume and process the header information to take decisions based on client platform.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Payments create -
```
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_uFcNSTN14N27NiyGdgkK8eN2fBmPWHHhbPZh6RMkBUxoByMfAdPlBItplwGctI6P' \
--data-raw '{
"amount": 6500,
"currency": "EUR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "GB",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "GB",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_qrNjDvodTni9SiSVeukh",
"merchant_id": "merchant_1726386502",
"status": "requires_payment_method",
"amount": 6500,
"net_amount": 6500,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"created": "2024-09-15T07:50:42.333Z",
"currency": "EUR",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_72r0N5WGBqazqsPQluK8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-15T08:05:42.333Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-15T07:50:42.348Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
2. PML -
```
curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251'
```
Response -
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "open_banking",
"payment_method_types": [
{
"payment_method_type": "open_banking_pis",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"plaid"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "Sarthak1",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false,
"is_tax_calculation_enabled": false
}
```
3. Payments confirm -
```
curl --location --request POST 'http://localhost:8080/payments/pay_qrNjDvodTni9SiSVeukh/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-client-platform: android' \
--header 'x-app-id: io.hyperswitch' \
--header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251' \
--data-raw '{
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"payment_method": "open_banking",
"payment_method_type": "open_banking_pis",
"payment_method_data": {
"open_banking": {
"open_banking_pis": {}
}
}
}'
```
Response -
```
{
"payment_id": "pay_qrNjDvodTni9SiSVeukh",
"merchant_id": "merchant_1726386502",
"status": "requires_customer_action",
"amount": 6500,
"net_amount": 6500,
"amount_capturable": 6500,
"amount_received": null,
"connector": "plaid",
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"created": "2024-09-15T07:50:42.333Z",
"currency": "EUR",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "open_banking",
"payment_method_data": {
"open_banking": {
"open_banking_pis": {}
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "third_party_sdk_session_token",
"session_token": {
"wallet_name": "open_banking",
"open_banking_session_token": "link-sandbox-9e376cad-8ab2-40f7-b0a0-4744d06a003b"
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "open_banking_pis",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2",
"payment_link": null,
"profile_id": "pro_72r0N5WGBqazqsPQluK8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_jp7RozkyIQV4e9zTXjyf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-15T08:05:42.333Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-15T07:51:02.510Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
``` | fbd2cda763f0d8d2757d734578babd73a8613cb8 |
1. Payments create -
```
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_uFcNSTN14N27NiyGdgkK8eN2fBmPWHHhbPZh6RMkBUxoByMfAdPlBItplwGctI6P' \
--data-raw '{
"amount": 6500,
"currency": "EUR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "GB",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "GB",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_qrNjDvodTni9SiSVeukh",
"merchant_id": "merchant_1726386502",
"status": "requires_payment_method",
"amount": 6500,
"net_amount": 6500,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"created": "2024-09-15T07:50:42.333Z",
"currency": "EUR",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_72r0N5WGBqazqsPQluK8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-15T08:05:42.333Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-15T07:50:42.348Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
2. PML -
```
curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251'
```
Response -
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "open_banking",
"payment_method_types": [
{
"payment_method_type": "open_banking_pis",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"plaid"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "Sarthak1",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false,
"is_tax_calculation_enabled": false
}
```
3. Payments confirm -
```
curl --location --request POST 'http://localhost:8080/payments/pay_qrNjDvodTni9SiSVeukh/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-client-platform: android' \
--header 'x-app-id: io.hyperswitch' \
--header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251' \
--data-raw '{
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"payment_method": "open_banking",
"payment_method_type": "open_banking_pis",
"payment_method_data": {
"open_banking": {
"open_banking_pis": {}
}
}
}'
```
Response -
```
{
"payment_id": "pay_qrNjDvodTni9SiSVeukh",
"merchant_id": "merchant_1726386502",
"status": "requires_customer_action",
"amount": 6500,
"net_amount": 6500,
"amount_capturable": 6500,
"amount_received": null,
"connector": "plaid",
"client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI",
"created": "2024-09-15T07:50:42.333Z",
"currency": "EUR",
"customer_id": null,
"customer": {
"id": null,
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "open_banking",
"payment_method_data": {
"open_banking": {
"open_banking_pis": {}
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "GB",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "third_party_sdk_session_token",
"session_token": {
"wallet_name": "open_banking",
"open_banking_session_token": "link-sandbox-9e376cad-8ab2-40f7-b0a0-4744d06a003b"
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "open_banking_pis",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2",
"payment_link": null,
"profile_id": "pro_72r0N5WGBqazqsPQluK8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_jp7RozkyIQV4e9zTXjyf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-15T08:05:42.333Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-15T07:51:02.510Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null
}
```
| [
"crates/api_models/src/payments.rs",
"crates/api_models/src/pm_auth.rs",
"crates/common_enums/src/enums.rs",
"crates/hyperswitch_domain_models/src/router_data.rs",
"crates/hyperswitch_domain_models/src/router_request_types.rs",
"crates/pm_auth/src/connector/plaid/transformers.rs",
"crates/pm_auth/src/ty... | |
juspay/hyperswitch | juspay__hyperswitch-5871 | Bug: feat(analytics): Add metrics, filters and APIs for Analytics v2 Dashboard - Payments Page
Add metrics, filters and APIs for Analytics v2 Dashboard - Payments page
The following filters should be added:
Payment Attempts:
- Merchant_id
- Card last 4
- Error Reason
- Card Issuer
Payment Intents:
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant id
- card_last_4
- error_reason
- card_issuer
New API endpoints for Payments Lifecycle (Sankey) on different levels should be created | diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 37a011c9a5a..546b57f99af 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -130,9 +130,12 @@ impl AnalyticsDataSource for ClickhouseClient {
fn get_table_engine(table: AnalyticsCollection) -> TableEngine {
match table {
AnalyticsCollection::Payment
+ | AnalyticsCollection::PaymentSessionized
| AnalyticsCollection::Refund
+ | AnalyticsCollection::RefundSessionized
| AnalyticsCollection::FraudCheck
| AnalyticsCollection::PaymentIntent
+ | AnalyticsCollection::PaymentIntentSessionized
| AnalyticsCollection::Dispute => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
@@ -423,13 +426,16 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
match self {
Self::Payment => Ok("payment_attempts".to_string()),
+ Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()),
Self::Refund => Ok("refunds".to_string()),
+ Self::RefundSessionized => Ok("sessionizer_refunds".to_string()),
Self::FraudCheck => Ok("fraud_check".to_string()),
Self::SdkEvents => Ok("sdk_events_audit".to_string()),
Self::SdkEventsAnalytics => Ok("sdk_events".to_string()),
Self::ApiEvents => Ok("api_events_audit".to_string()),
Self::ApiEventsAnalytics => Ok("api_events".to_string()),
Self::PaymentIntent => Ok("payment_intents".to_string()),
+ Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()),
Self::ConnectorEvents => Ok("connector_events_audit".to_string()),
Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()),
Self::Dispute => Ok("dispute".to_string()),
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index d5cb3c718df..224cd82ccd3 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -996,6 +996,7 @@ pub enum AnalyticsFlow {
GetSearchResults,
GetDisputeFilters,
GetDisputeMetrics,
+ GetSankey,
}
impl FlowMetric for AnalyticsFlow {}
diff --git a/crates/analytics/src/payment_intents.rs b/crates/analytics/src/payment_intents.rs
index 449dd94788c..809be1b20a1 100644
--- a/crates/analytics/src/payment_intents.rs
+++ b/crates/analytics/src/payment_intents.rs
@@ -2,6 +2,7 @@ pub mod accumulator;
mod core;
pub mod filters;
pub mod metrics;
+pub mod sankey;
pub mod types;
pub use accumulator::{PaymentIntentMetricAccumulator, PaymentIntentMetricsAccumulator};
@@ -10,4 +11,4 @@ pub trait PaymentIntentAnalytics:
{
}
-pub use self::core::{get_filters, get_metrics};
+pub use self::core::{get_filters, get_metrics, get_sankey};
diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs
index 8fd98a1e73c..cbb8335cea0 100644
--- a/crates/analytics/src/payment_intents/accumulator.rs
+++ b/crates/analytics/src/payment_intents/accumulator.rs
@@ -1,5 +1,6 @@
use api_models::analytics::payment_intents::PaymentIntentMetricsBucketValue;
use bigdecimal::ToPrimitive;
+use diesel_models::enums as storage_enums;
use super::metrics::PaymentIntentMetricRow;
@@ -7,8 +8,11 @@ use super::metrics::PaymentIntentMetricRow;
pub struct PaymentIntentMetricsAccumulator {
pub successful_smart_retries: CountAccumulator,
pub total_smart_retries: CountAccumulator,
- pub smart_retried_amount: SumAccumulator,
+ pub smart_retried_amount: SmartRetriedAmountAccumulator,
pub payment_intent_count: CountAccumulator,
+ pub payments_success_rate: PaymentsSuccessRateAccumulator,
+ pub payment_processed_amount: ProcessedAmountAccumulator,
+ pub payments_distribution: PaymentsDistributionAccumulator,
}
#[derive(Debug, Default)]
@@ -38,9 +42,31 @@ pub trait PaymentIntentMetricAccumulator {
}
#[derive(Debug, Default)]
-#[repr(transparent)]
-pub struct SumAccumulator {
- pub total: Option<i64>,
+pub struct SmartRetriedAmountAccumulator {
+ pub amount: Option<i64>,
+ pub amount_without_retries: Option<i64>,
+}
+
+#[derive(Debug, Default)]
+pub struct PaymentsSuccessRateAccumulator {
+ pub success: u32,
+ pub success_without_retries: u32,
+ pub total: u32,
+}
+
+#[derive(Debug, Default)]
+pub struct ProcessedAmountAccumulator {
+ pub count_with_retries: Option<i64>,
+ pub total_with_retries: Option<i64>,
+ pub count_without_retries: Option<i64>,
+ pub total_without_retries: Option<i64>,
+}
+
+#[derive(Debug, Default)]
+pub struct PaymentsDistributionAccumulator {
+ pub success_without_retries: u32,
+ pub failed_without_retries: u32,
+ pub total: u32,
}
impl PaymentIntentMetricAccumulator for CountAccumulator {
@@ -59,32 +85,251 @@ impl PaymentIntentMetricAccumulator for CountAccumulator {
}
}
-impl PaymentIntentMetricAccumulator for SumAccumulator {
- type MetricOutput = Option<u64>;
+impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
- self.total = match (
- self.total,
+ self.amount = match (
+ self.amount,
metrics.total.as_ref().and_then(ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
+ };
+ if metrics.first_attempt.unwrap_or(0) == 1 {
+ self.amount_without_retries = match (
+ self.amount_without_retries,
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ }
+ } else {
+ self.amount_without_retries = Some(0);
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
- self.total.and_then(|i| u64::try_from(i).ok())
+ let with_retries = self.amount.and_then(|i| u64::try_from(i).ok()).or(Some(0));
+ let without_retries = self
+ .amount_without_retries
+ .and_then(|i| u64::try_from(i).ok())
+ .or(Some(0));
+ (with_retries, without_retries)
+ }
+}
+
+impl PaymentIntentMetricAccumulator for PaymentsSuccessRateAccumulator {
+ type MetricOutput = (
+ Option<u32>,
+ Option<u32>,
+ Option<u32>,
+ Option<f64>,
+ Option<f64>,
+ );
+
+ fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
+ if let Some(ref status) = metrics.status {
+ if status.as_ref() == &storage_enums::IntentStatus::Succeeded {
+ if let Some(success) = metrics
+ .count
+ .and_then(|success| u32::try_from(success).ok())
+ {
+ self.success += success;
+ if metrics.first_attempt.unwrap_or(0) == 1 {
+ self.success_without_retries += success;
+ }
+ }
+ }
+ if status.as_ref() != &storage_enums::IntentStatus::RequiresCustomerAction
+ && status.as_ref() != &storage_enums::IntentStatus::RequiresPaymentMethod
+ && status.as_ref() != &storage_enums::IntentStatus::RequiresMerchantAction
+ && status.as_ref() != &storage_enums::IntentStatus::RequiresConfirmation
+ {
+ if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
+ self.total += total;
+ }
+ }
+ }
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total == 0 {
+ (None, None, None, None, None)
+ } else {
+ let success = Some(self.success);
+ let success_without_retries = Some(self.success_without_retries);
+ let total = Some(self.total);
+
+ let success_rate = match (success, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ let success_without_retries_rate = match (success_without_retries, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ (
+ success,
+ success_without_retries,
+ total,
+ success_rate,
+ success_without_retries_rate,
+ )
+ }
+ }
+}
+
+impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
+ #[inline]
+ fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
+ self.total_with_retries = match (
+ self.total_with_retries,
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ self.count_with_retries = match (self.count_with_retries, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ if metrics.first_attempt.unwrap_or(0) == 1 {
+ self.total_without_retries = match (
+ self.total_without_retries,
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ self.count_without_retries = match (self.count_without_retries, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+ }
+ }
+ #[inline]
+ fn collect(self) -> Self::MetricOutput {
+ let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok();
+ let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok());
+
+ let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok();
+ let count_without_retries = self
+ .count_without_retries
+ .and_then(|i| u64::try_from(i).ok());
+
+ (
+ total_with_retries,
+ count_with_retries,
+ total_without_retries,
+ count_without_retries,
+ )
+ }
+}
+
+impl PaymentIntentMetricAccumulator for PaymentsDistributionAccumulator {
+ type MetricOutput = (Option<f64>, Option<f64>);
+
+ fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
+ let first_attempt = metrics.first_attempt.unwrap_or(0);
+ if let Some(ref status) = metrics.status {
+ if status.as_ref() == &storage_enums::IntentStatus::Succeeded {
+ if let Some(success) = metrics
+ .count
+ .and_then(|success| u32::try_from(success).ok())
+ {
+ if first_attempt == 1 {
+ self.success_without_retries += success;
+ }
+ }
+ }
+ if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) {
+ if first_attempt == 0
+ || (first_attempt == 1
+ && status.as_ref() == &storage_enums::IntentStatus::Failed)
+ {
+ self.failed_without_retries += failed;
+ }
+ }
+
+ if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
+ self.total += total;
+ }
+ }
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total == 0 {
+ (None, None)
+ } else {
+ let success_without_retries = Some(self.success_without_retries);
+ let failed_without_retries = Some(self.failed_without_retries);
+ let total = Some(self.total);
+
+ let success_rate_without_retries = match (success_without_retries, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ let failed_rate_without_retries = match (failed_without_retries, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+ (success_rate_without_retries, failed_rate_without_retries)
+ }
}
}
impl PaymentIntentMetricsAccumulator {
pub fn collect(self) -> PaymentIntentMetricsBucketValue {
+ let (
+ successful_payments,
+ successful_payments_without_smart_retries,
+ total_payments,
+ payments_success_rate,
+ payments_success_rate_without_smart_retries,
+ ) = self.payments_success_rate.collect();
+ let (smart_retried_amount, smart_retried_amount_without_smart_retries) =
+ self.smart_retried_amount.collect();
+ let (
+ payment_processed_amount,
+ payment_processed_count,
+ payment_processed_amount_without_smart_retries,
+ payment_processed_count_without_smart_retries,
+ ) = self.payment_processed_amount.collect();
+ let (
+ payments_success_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution_without_smart_retries,
+ ) = self.payments_distribution.collect();
PaymentIntentMetricsBucketValue {
successful_smart_retries: self.successful_smart_retries.collect(),
total_smart_retries: self.total_smart_retries.collect(),
- smart_retried_amount: self.smart_retried_amount.collect(),
+ smart_retried_amount,
+ smart_retried_amount_without_smart_retries,
payment_intent_count: self.payment_intent_count.collect(),
+ successful_payments,
+ successful_payments_without_smart_retries,
+ total_payments,
+ payments_success_rate,
+ payments_success_rate_without_smart_retries,
+ payment_processed_amount,
+ payment_processed_count,
+ payment_processed_amount_without_smart_retries,
+ payment_processed_count_without_smart_retries,
+ payments_success_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution_without_smart_retries,
}
}
}
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index f8a5c48986a..e04c3b7bd9e 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -6,10 +6,12 @@ use api_models::analytics::{
MetricsBucketResponse, PaymentIntentDimensions, PaymentIntentMetrics,
PaymentIntentMetricsBucketIdentifier,
},
- AnalyticsMetadata, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest,
- MetricsResponse, PaymentIntentFilterValue, PaymentIntentFiltersResponse,
+ GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, PaymentIntentFilterValue,
+ PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse,
+ SankeyResponse,
};
-use common_utils::errors::CustomResult;
+use common_enums::IntentStatus;
+use common_utils::{errors::CustomResult, types::TimeRange};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
@@ -20,6 +22,7 @@ use router_env::{
use super::{
filters::{get_payment_intent_filter_for_dimension, PaymentIntentFilterRow},
metrics::PaymentIntentMetricRow,
+ sankey::{get_sankey_data, SessionizerRefundStatus},
PaymentIntentMetricsAccumulator,
};
use crate::{
@@ -41,12 +44,85 @@ pub enum TaskType {
),
}
+#[instrument(skip_all)]
+pub async fn get_sankey(
+ pool: &AnalyticsProvider,
+ auth: &AuthInfo,
+ req: TimeRange,
+) -> AnalyticsResult<SankeyResponse> {
+ match pool {
+ AnalyticsProvider::Sqlx(_) => Err(AnalyticsError::NotImplemented(
+ "Sankey not implemented for sqlx",
+ ))?,
+ AnalyticsProvider::Clickhouse(ckh_pool)
+ | AnalyticsProvider::CombinedCkh(_, ckh_pool)
+ | AnalyticsProvider::CombinedSqlx(_, ckh_pool) => {
+ let sankey_rows = get_sankey_data(ckh_pool, auth, &req)
+ .await
+ .change_context(AnalyticsError::UnknownError)?;
+ let mut sankey_response = SankeyResponse::default();
+ for i in sankey_rows {
+ match (
+ i.status.as_ref(),
+ i.refunds_status.unwrap_or_default().as_ref(),
+ i.attempt_count,
+ ) {
+ (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => {
+ sankey_response.refunded += i.count
+ }
+ (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => {
+ sankey_response.partial_refunded += i.count
+ }
+ (
+ IntentStatus::Succeeded
+ | IntentStatus::PartiallyCaptured
+ | IntentStatus::PartiallyCapturedAndCapturable
+ | IntentStatus::RequiresCapture,
+ SessionizerRefundStatus::NotRefunded,
+ 1,
+ ) => sankey_response.normal_success += i.count,
+ (
+ IntentStatus::Succeeded
+ | IntentStatus::PartiallyCaptured
+ | IntentStatus::PartiallyCapturedAndCapturable
+ | IntentStatus::RequiresCapture,
+ SessionizerRefundStatus::NotRefunded,
+ _,
+ ) => sankey_response.smart_retried_success += i.count,
+ (IntentStatus::Failed, _, 1) => sankey_response.normal_failure += i.count,
+ (IntentStatus::Failed, _, _) => {
+ sankey_response.smart_retried_failure += i.count
+ }
+ (IntentStatus::Cancelled, _, _) => sankey_response.cancelled += i.count,
+ (IntentStatus::Processing, _, _) => sankey_response.pending += i.count,
+ (IntentStatus::RequiresCustomerAction, _, _) => {
+ sankey_response.customer_awaited += i.count
+ }
+ (IntentStatus::RequiresMerchantAction, _, _) => {
+ sankey_response.merchant_awaited += i.count
+ }
+ (IntentStatus::RequiresPaymentMethod, _, _) => {
+ sankey_response.pm_awaited += i.count
+ }
+ (IntentStatus::RequiresConfirmation, _, _) => {
+ sankey_response.confirmation_awaited += i.count
+ }
+ i @ (_, _, _) => {
+ router_env::logger::error!(status=?i, "Unknown status in sankey data");
+ }
+ }
+ }
+ Ok(sankey_response)
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
auth: &AuthInfo,
req: GetPaymentIntentMetricRequest,
-) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
+) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
PaymentIntentMetricsBucketIdentifier,
PaymentIntentMetricsAccumulator,
@@ -107,18 +183,34 @@ pub async fn get_metrics(
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
- PaymentIntentMetrics::SuccessfulSmartRetries => metrics_builder
- .successful_smart_retries
- .add_metrics_bucket(&value),
- PaymentIntentMetrics::TotalSmartRetries => metrics_builder
+ PaymentIntentMetrics::SuccessfulSmartRetries
+ | PaymentIntentMetrics::SessionizedSuccessfulSmartRetries => {
+ metrics_builder
+ .successful_smart_retries
+ .add_metrics_bucket(&value)
+ }
+ PaymentIntentMetrics::TotalSmartRetries
+ | PaymentIntentMetrics::SessionizedTotalSmartRetries => metrics_builder
.total_smart_retries
.add_metrics_bucket(&value),
- PaymentIntentMetrics::SmartRetriedAmount => metrics_builder
+ PaymentIntentMetrics::SmartRetriedAmount
+ | PaymentIntentMetrics::SessionizedSmartRetriedAmount => metrics_builder
.smart_retried_amount
.add_metrics_bucket(&value),
- PaymentIntentMetrics::PaymentIntentCount => metrics_builder
+ PaymentIntentMetrics::PaymentIntentCount
+ | PaymentIntentMetrics::SessionizedPaymentIntentCount => metrics_builder
.payment_intent_count
.add_metrics_bucket(&value),
+ PaymentIntentMetrics::PaymentsSuccessRate
+ | PaymentIntentMetrics::SessionizedPaymentsSuccessRate => metrics_builder
+ .payments_success_rate
+ .add_metrics_bucket(&value),
+ PaymentIntentMetrics::SessionizedPaymentProcessedAmount => metrics_builder
+ .payment_processed_amount
+ .add_metrics_bucket(&value),
+ PaymentIntentMetrics::SessionizedPaymentsDistribution => metrics_builder
+ .payments_distribution
+ .add_metrics_bucket(&value),
}
}
@@ -131,18 +223,80 @@ pub async fn get_metrics(
}
}
+ let mut success = 0;
+ let mut success_without_smart_retries = 0;
+ let mut total_smart_retried_amount = 0;
+ let mut total_smart_retried_amount_without_smart_retries = 0;
+ let mut total = 0;
+ let mut total_payment_processed_amount = 0;
+ let mut total_payment_processed_count = 0;
+ let mut total_payment_processed_amount_without_smart_retries = 0;
+ let mut total_payment_processed_count_without_smart_retries = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
- .map(|(id, val)| MetricsBucketResponse {
- values: val.collect(),
- dimensions: id,
+ .map(|(id, val)| {
+ let collected_values = val.collect();
+ if let Some(success_count) = collected_values.successful_payments {
+ success += success_count;
+ }
+ if let Some(success_count) = collected_values.successful_payments_without_smart_retries
+ {
+ success_without_smart_retries += success_count;
+ }
+ if let Some(total_count) = collected_values.total_payments {
+ total += total_count;
+ }
+ if let Some(retried_amount) = collected_values.smart_retried_amount {
+ total_smart_retried_amount += retried_amount;
+ }
+ if let Some(retried_amount) =
+ collected_values.smart_retried_amount_without_smart_retries
+ {
+ total_smart_retried_amount_without_smart_retries += retried_amount;
+ }
+ if let Some(amount) = collected_values.payment_processed_amount {
+ total_payment_processed_amount += amount;
+ }
+ if let Some(count) = collected_values.payment_processed_count {
+ total_payment_processed_count += count;
+ }
+ if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries {
+ total_payment_processed_amount_without_smart_retries += amount;
+ }
+ if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
+ total_payment_processed_count_without_smart_retries += count;
+ }
+ MetricsBucketResponse {
+ values: collected_values,
+ dimensions: id,
+ }
})
.collect();
-
- Ok(MetricsResponse {
+ let total_success_rate = match (success, total) {
+ (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+ let total_success_rate_without_smart_retries = match (success_without_smart_retries, total) {
+ (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+ Ok(PaymentIntentsMetricsResponse {
query_data,
- meta_data: [AnalyticsMetadata {
- current_time_range: req.time_range,
+ meta_data: [PaymentIntentsAnalyticsMetadata {
+ total_success_rate,
+ total_success_rate_without_smart_retries,
+ total_smart_retried_amount: Some(total_smart_retried_amount),
+ total_smart_retried_amount_without_smart_retries: Some(
+ total_smart_retried_amount_without_smart_retries,
+ ),
+ total_payment_processed_amount: Some(total_payment_processed_amount),
+ total_payment_processed_amount_without_smart_retries: Some(
+ total_payment_processed_amount_without_smart_retries,
+ ),
+ total_payment_processed_count: Some(total_payment_processed_count),
+ total_payment_processed_count_without_smart_retries: Some(
+ total_payment_processed_count_without_smart_retries,
+ ),
}],
})
}
@@ -217,6 +371,15 @@ pub async fn get_filters(
PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()),
PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
PaymentIntentDimensions::ProfileId => fil.profile_id,
+ PaymentIntentDimensions::Connector => fil.connector,
+ PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()),
+ PaymentIntentDimensions::PaymentMethod => fil.payment_method,
+ PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type,
+ PaymentIntentDimensions::CardNetwork => fil.card_network,
+ PaymentIntentDimensions::MerchantId => fil.merchant_id,
+ PaymentIntentDimensions::CardLast4 => fil.card_last_4,
+ PaymentIntentDimensions::CardIssuer => fil.card_issuer,
+ PaymentIntentDimensions::ErrorReason => fil.error_reason,
})
.collect::<Vec<String>>();
res.query_data.push(PaymentIntentFilterValue {
diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs
index e81b050214c..25d43e76f03 100644
--- a/crates/analytics/src/payment_intents/filters.rs
+++ b/crates/analytics/src/payment_intents/filters.rs
@@ -1,6 +1,6 @@
use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange};
use common_utils::errors::ReportSwitchExt;
-use diesel_models::enums::{Currency, IntentStatus};
+use diesel_models::enums::{AuthenticationType, Currency, IntentStatus};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -54,4 +54,13 @@ pub struct PaymentIntentFilterRow {
pub status: Option<DBEnumWrapper<IntentStatus>>,
pub currency: Option<DBEnumWrapper<Currency>>,
pub profile_id: Option<String>,
+ pub connector: Option<String>,
+ pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>,
+ pub payment_method: Option<String>,
+ pub payment_method_type: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
}
diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs
index f27a02368ae..8ee9d24b5a0 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -17,11 +17,14 @@ use crate::{
};
mod payment_intent_count;
+mod payments_success_rate;
+mod sessionized_metrics;
mod smart_retried_amount;
mod successful_smart_retries;
mod total_smart_retries;
use payment_intent_count::PaymentIntentCount;
+use payments_success_rate::PaymentsSuccessRate;
use smart_retried_amount::SmartRetriedAmount;
use successful_smart_retries::SuccessfulSmartRetries;
use total_smart_retries::TotalSmartRetries;
@@ -31,6 +34,16 @@ pub struct PaymentIntentMetricRow {
pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>,
pub currency: Option<DBEnumWrapper<storage_enums::Currency>>,
pub profile_id: Option<String>,
+ pub connector: Option<String>,
+ pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>,
+ pub payment_method: Option<String>,
+ pub payment_method_type: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
+ pub first_attempt: Option<i64>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
@@ -98,6 +111,46 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::PaymentsSuccessRate => {
+ PaymentsSuccessRate
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedSuccessfulSmartRetries => {
+ sessionized_metrics::SuccessfulSmartRetries
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedTotalSmartRetries => {
+ sessionized_metrics::TotalSmartRetries
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedSmartRetriedAmount => {
+ sessionized_metrics::SmartRetriedAmount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentIntentCount => {
+ sessionized_metrics::PaymentIntentCount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentsSuccessRate => {
+ sessionized_metrics::PaymentsSuccessRate
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentProcessedAmount => {
+ sessionized_metrics::PaymentProcessedAmount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentsDistribution => {
+ sessionized_metrics::PaymentsDistribution
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
index 4632cbe9f37..b301a9b9b23 100644
--- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
+++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
@@ -101,6 +101,15 @@ where
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
new file mode 100644
index 00000000000..07b1bfcf69f
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
@@ -0,0 +1,146 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(super) struct PaymentsSuccessRate;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntent);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_select_column("(attempt_count == 1) as first_attempt".to_string())
+ .switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ None,
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs
new file mode 100644
index 00000000000..fcd9a2b8adf
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs
@@ -0,0 +1,17 @@
+mod payment_intent_count;
+mod payment_processed_amount;
+mod payments_distribution;
+mod payments_success_rate;
+mod smart_retried_amount;
+mod successful_smart_retries;
+mod total_smart_retries;
+
+pub(super) use payment_intent_count::PaymentIntentCount;
+pub(super) use payment_processed_amount::PaymentProcessedAmount;
+pub(super) use payments_distribution::PaymentsDistribution;
+pub(super) use payments_success_rate::PaymentsSuccessRate;
+pub(super) use smart_retried_amount::SmartRetriedAmount;
+pub(super) use successful_smart_retries::SuccessfulSmartRetries;
+pub(super) use total_smart_retries::TotalSmartRetries;
+
+pub use super::{PaymentIntentMetric, PaymentIntentMetricAnalytics, PaymentIntentMetricRow};
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs
new file mode 100644
index 00000000000..7475a75bb53
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs
@@ -0,0 +1,133 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentIntentCount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for PaymentIntentCount
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ i.status.as_ref().map(|i| i.0),
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
new file mode 100644
index 00000000000..506965375f5
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
@@ -0,0 +1,160 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentProcessedAmount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for PaymentProcessedAmount
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_select_column("attempt_count == 1 as first_attempt")
+ .switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("attempt_count")
+ .attach_printable("Error grouping by attempt_count")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ PaymentIntentDimensions::PaymentIntentStatus,
+ storage_enums::IntentStatus::Succeeded,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ None,
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
new file mode 100644
index 00000000000..0b55c101a7c
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
@@ -0,0 +1,145 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentsDistribution;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for PaymentsDistribution
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_select_column("attempt_count == 1 as first_attempt")
+ .switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ None,
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs
new file mode 100644
index 00000000000..8c340d0b2d6
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs
@@ -0,0 +1,146 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentsSuccessRate;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_select_column("(attempt_count == 1) as first_attempt".to_string())
+ .switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ None,
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs
new file mode 100644
index 00000000000..8105a4c82a4
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs
@@ -0,0 +1,154 @@
+use std::collections::HashSet;
+
+use api_models::{
+ analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+ },
+ enums::IntentStatus,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
+ Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct SmartRetriedAmount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for SmartRetriedAmount
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_select_column("attempt_count == 1 as first_attempt")
+ .switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
+ .switch()?;
+ query_builder
+ .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
+ .switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ i.status.as_ref().map(|i| i.0),
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
new file mode 100644
index 00000000000..0b28cb5366d
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
@@ -0,0 +1,143 @@
+use std::collections::HashSet;
+
+use api_models::{
+ analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+ },
+ enums::IntentStatus,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
+ Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct SuccessfulSmartRetries;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for SuccessfulSmartRetries
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
+ .switch()?;
+ query_builder
+ .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
+ .switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ i.status.as_ref().map(|i| i.0),
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs
new file mode 100644
index 00000000000..20ef8be6277
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs
@@ -0,0 +1,138 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payment_intents::{
+ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
+ },
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentIntentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
+ Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct TotalSmartRetries;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentIntentMetric<T> for TotalSmartRetries
+where
+ T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentIntentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentIntentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
+ .switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentIntentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentIntentMetricsBucketIdentifier::new(
+ i.status.as_ref().map(|i| i.0),
+ i.currency.as_ref().map(|i| i.0),
+ i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
index e1df9fe50d3..8468911f7bb 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -58,6 +58,11 @@ where
alias: Some("total"),
})
.switch()?;
+
+ query_builder
+ .add_select_column("attempt_count == 1 as first_attempt")
+ .switch()?;
+
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -93,6 +98,11 @@ where
.switch()?;
}
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
@@ -112,6 +122,15 @@ where
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
index 4fe5f3a26f5..a19bdec518c 100644
--- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
@@ -111,6 +111,15 @@ where
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
index e98efa9f6ab..f5539abd9f5 100644
--- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
@@ -106,6 +106,15 @@ where
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payment_intents/sankey.rs b/crates/analytics/src/payment_intents/sankey.rs
new file mode 100644
index 00000000000..53fd03562f1
--- /dev/null
+++ b/crates/analytics/src/payment_intents/sankey.rs
@@ -0,0 +1,127 @@
+use common_enums::enums;
+use common_utils::{
+ errors::ParsingError,
+ types::{authentication::AuthInfo, TimeRange},
+};
+use error_stack::ResultExt;
+use router_env::logger;
+use time::PrimitiveDateTime;
+
+use crate::{
+ clickhouse::ClickhouseClient,
+ query::{Aggregate, QueryBuilder, QueryFilter},
+ types::{AnalyticsCollection, DBEnumWrapper, MetricsError, MetricsResult},
+};
+
+#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)]
+pub struct PaymentIntentMetricRow {
+ pub profile_id: Option<String>,
+ pub connector: Option<String>,
+ pub authentication_type: Option<DBEnumWrapper<enums::AuthenticationType>>,
+ pub payment_method: Option<String>,
+ pub payment_method_type: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
+ pub first_attempt: Option<i64>,
+ pub total: Option<bigdecimal::BigDecimal>,
+ pub count: Option<i64>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub start_bucket: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub end_bucket: Option<PrimitiveDateTime>,
+}
+
+#[derive(
+ Debug, Default, serde::Deserialize, strum::AsRefStr, strum::EnumString, strum::Display,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionizerRefundStatus {
+ FullRefunded,
+ #[default]
+ NotRefunded,
+ PartialRefunded,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct SankeyRow {
+ pub status: DBEnumWrapper<enums::IntentStatus>,
+ #[serde(default)]
+ pub refunds_status: Option<DBEnumWrapper<SessionizerRefundStatus>>,
+ pub attempt_count: i64,
+ pub count: i64,
+}
+
+impl TryInto<SankeyRow> for serde_json::Value {
+ type Error = error_stack::Report<ParsingError>;
+
+ fn try_into(self) -> Result<SankeyRow, Self::Error> {
+ logger::debug!("Parsing SankeyRow from {:?}", self);
+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
+ "Failed to parse Sankey in clickhouse results",
+ ))
+ }
+}
+
+pub async fn get_sankey_data(
+ clickhouse_client: &ClickhouseClient,
+ auth: &AuthInfo,
+ time_range: &TimeRange,
+) -> MetricsResult<Vec<SankeyRow>> {
+ let mut query_builder =
+ QueryBuilder::<ClickhouseClient>::new(AnalyticsCollection::PaymentIntentSessionized);
+ query_builder
+ .add_select_column(Aggregate::<String>::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_select_column("status")
+ .attach_printable("Error adding select clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_select_column("refunds_status")
+ .attach_printable("Error adding select clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_select_column("attempt_count")
+ .attach_printable("Error adding select clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ auth.set_filter_clause(&mut query_builder)
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_group_by_clause("status")
+ .attach_printable("Error adding group by clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_group_by_clause("refunds_status")
+ .attach_printable("Error adding group by clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .add_group_by_clause("attempt_count")
+ .attach_printable("Error adding group by clause")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ query_builder
+ .execute_query::<SankeyRow, _>(clickhouse_client)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(Ok)
+ .collect()
+}
diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs
index 03f2a196c20..1a9a2f2ed65 100644
--- a/crates/analytics/src/payment_intents/types.rs
+++ b/crates/analytics/src/payment_intents/types.rs
@@ -30,6 +30,63 @@ where
.add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id)
.attach_printable("Error adding profile id filter")?;
}
+ if !self.connector.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentIntentDimensions::Connector, &self.connector)
+ .attach_printable("Error adding connector filter")?;
+ }
+ if !self.auth_type.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentIntentDimensions::AuthType, &self.auth_type)
+ .attach_printable("Error adding auth type filter")?;
+ }
+ if !self.payment_method.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ PaymentIntentDimensions::PaymentMethod,
+ &self.payment_method,
+ )
+ .attach_printable("Error adding payment method filter")?;
+ }
+ if !self.payment_method_type.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ PaymentIntentDimensions::PaymentMethodType,
+ &self.payment_method_type,
+ )
+ .attach_printable("Error adding payment method type filter")?;
+ }
+ if !self.card_network.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ PaymentIntentDimensions::CardNetwork,
+ &self.card_network,
+ )
+ .attach_printable("Error adding card network filter")?;
+ }
+ if !self.merchant_id.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentIntentDimensions::MerchantId, &self.merchant_id)
+ .attach_printable("Error adding merchant id filter")?;
+ }
+ if !self.card_last_4.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentIntentDimensions::CardLast4, &self.card_last_4)
+ .attach_printable("Error adding card last 4 filter")?;
+ }
+ if !self.card_issuer.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentIntentDimensions::CardIssuer, &self.card_issuer)
+ .attach_printable("Error adding card issuer filter")?;
+ }
+ if !self.error_reason.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ PaymentIntentDimensions::ErrorReason,
+ &self.error_reason,
+ )
+ .attach_printable("Error adding error reason filter")?;
+ }
Ok(())
}
}
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index efc8aaf6983..4388b2071fe 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -10,12 +10,14 @@ pub struct PaymentMetricsAccumulator {
pub payment_success_rate: SuccessRateAccumulator,
pub payment_count: CountAccumulator,
pub payment_success: CountAccumulator,
- pub processed_amount: SumAccumulator,
+ pub processed_amount: ProcessedAmountAccumulator,
pub avg_ticket_size: AverageAccumulator,
pub payment_error_message: ErrorDistributionAccumulator,
pub retries_count: CountAccumulator,
- pub retries_amount_processed: SumAccumulator,
+ pub retries_amount_processed: RetriesAmountAccumulator,
pub connector_success_rate: SuccessRateAccumulator,
+ pub payments_distribution: PaymentsDistributionAccumulator,
+ pub failure_reasons_distribution: FailureReasonsDistributionAccumulator,
}
#[derive(Debug, Default)]
@@ -30,6 +32,12 @@ pub struct ErrorDistributionAccumulator {
pub error_vec: Vec<ErrorDistributionRow>,
}
+#[derive(Debug, Default)]
+pub struct FailureReasonsDistributionAccumulator {
+ pub count: u64,
+ pub count_without_retries: u64,
+}
+
#[derive(Debug, Default)]
pub struct SuccessRateAccumulator {
pub success: i64,
@@ -43,9 +51,11 @@ pub struct CountAccumulator {
}
#[derive(Debug, Default)]
-#[repr(transparent)]
-pub struct SumAccumulator {
- pub total: Option<i64>,
+pub struct ProcessedAmountAccumulator {
+ pub count_with_retries: Option<i64>,
+ pub total_with_retries: Option<i64>,
+ pub count_without_retries: Option<i64>,
+ pub total_without_retries: Option<i64>,
}
#[derive(Debug, Default)]
@@ -54,6 +64,22 @@ pub struct AverageAccumulator {
pub count: u32,
}
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct RetriesAmountAccumulator {
+ pub total: Option<i64>,
+}
+
+#[derive(Debug, Default)]
+pub struct PaymentsDistributionAccumulator {
+ pub success: u32,
+ pub failed: u32,
+ pub total: u32,
+ pub success_without_retries: u32,
+ pub failed_without_retries: u32,
+ pub total_without_retries: u32,
+}
+
pub trait PaymentMetricAccumulator {
type MetricOutput;
@@ -107,6 +133,29 @@ impl PaymentDistributionAccumulator for ErrorDistributionAccumulator {
}
}
+impl PaymentMetricAccumulator for FailureReasonsDistributionAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>);
+
+ fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
+ if let Some(count) = metrics.count {
+ if let Ok(count_u64) = u64::try_from(count) {
+ self.count += count_u64;
+ }
+ }
+ if metrics.first_attempt.unwrap_or(false) {
+ if let Some(count) = metrics.count {
+ if let Ok(count_u64) = u64::try_from(count) {
+ self.count_without_retries += count_u64;
+ }
+ }
+ }
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ (Some(self.count), Some(self.count_without_retries))
+ }
+}
+
impl PaymentMetricAccumulator for SuccessRateAccumulator {
type MetricOutput = Option<f64>;
@@ -131,6 +180,81 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator {
}
}
+impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
+ type MetricOutput = (Option<f64>, Option<f64>, Option<f64>, Option<f64>);
+
+ fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
+ if let Some(ref status) = metrics.status {
+ if status.as_ref() == &storage_enums::AttemptStatus::Charged {
+ if let Some(success) = metrics
+ .count
+ .and_then(|success| u32::try_from(success).ok())
+ {
+ self.success += success;
+ if metrics.first_attempt.unwrap_or(false) {
+ self.success_without_retries += success;
+ }
+ }
+ }
+ if status.as_ref() == &storage_enums::AttemptStatus::Failure {
+ if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) {
+ self.failed += failed;
+ if metrics.first_attempt.unwrap_or(false) {
+ self.failed_without_retries += failed;
+ }
+ }
+ }
+ if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) {
+ self.total += total;
+ if metrics.first_attempt.unwrap_or(false) {
+ self.total_without_retries += total;
+ }
+ }
+ }
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total == 0 {
+ (None, None, None, None)
+ } else {
+ let success = Some(self.success);
+ let success_without_retries = Some(self.success_without_retries);
+ let failed = Some(self.failed);
+ let failed_without_retries = Some(self.failed_without_retries);
+ let total = Some(self.total);
+ let total_without_retries = Some(self.total_without_retries);
+
+ let success_rate = match (success, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ let success_rate_without_retries =
+ match (success_without_retries, total_without_retries) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ let failed_rate = match (failed, total) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+
+ let failed_rate_without_retries = match (failed_without_retries, total_without_retries)
+ {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
+ (
+ success_rate,
+ success_rate_without_retries,
+ failed_rate,
+ failed_rate_without_retries,
+ )
+ }
+ }
+}
+
impl PaymentMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
@@ -147,9 +271,63 @@ impl PaymentMetricAccumulator for CountAccumulator {
}
}
-impl PaymentMetricAccumulator for SumAccumulator {
- type MetricOutput = Option<u64>;
+impl PaymentMetricAccumulator for ProcessedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
#[inline]
+ fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
+ self.total_with_retries = match (
+ self.total_with_retries,
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ self.count_with_retries = match (self.count_with_retries, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ if metrics.first_attempt.unwrap_or(false) {
+ self.total_without_retries = match (
+ self.total_without_retries,
+ metrics.total.as_ref().and_then(ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+
+ self.count_without_retries = match (self.count_without_retries, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ };
+ }
+ }
+ #[inline]
+ fn collect(self) -> Self::MetricOutput {
+ let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok();
+ let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok());
+
+ let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok();
+ let count_without_retries = self
+ .count_without_retries
+ .and_then(|i| u64::try_from(i).ok());
+
+ (
+ total_with_retries,
+ count_with_retries,
+ total_without_retries,
+ count_without_retries,
+ )
+ }
+}
+
+impl PaymentMetricAccumulator for RetriesAmountAccumulator {
+ type MetricOutput = Option<u64>;
fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
self.total = match (
self.total,
@@ -158,7 +336,7 @@ impl PaymentMetricAccumulator for SumAccumulator {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
- }
+ };
}
#[inline]
fn collect(self) -> Self::MetricOutput {
@@ -195,16 +373,39 @@ impl PaymentMetricAccumulator for AverageAccumulator {
impl PaymentMetricsAccumulator {
pub fn collect(self) -> PaymentMetricsBucketValue {
+ let (
+ payment_processed_amount,
+ payment_processed_count,
+ payment_processed_amount_without_smart_retries,
+ payment_processed_count_without_smart_retries,
+ ) = self.processed_amount.collect();
+ let (
+ payments_success_rate_distribution,
+ payments_success_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution,
+ payments_failure_rate_distribution_without_smart_retries,
+ ) = self.payments_distribution.collect();
+ let (failure_reason_count, failure_reason_count_without_smart_retries) =
+ self.failure_reasons_distribution.collect();
PaymentMetricsBucketValue {
payment_success_rate: self.payment_success_rate.collect(),
payment_count: self.payment_count.collect(),
payment_success_count: self.payment_success.collect(),
- payment_processed_amount: self.processed_amount.collect(),
+ payment_processed_amount,
+ payment_processed_count,
+ payment_processed_amount_without_smart_retries,
+ payment_processed_count_without_smart_retries,
avg_ticket_size: self.avg_ticket_size.collect(),
payment_error_message: self.payment_error_message.collect(),
retries_count: self.retries_count.collect(),
retries_amount_processed: self.retries_amount_processed.collect(),
connector_success_rate: self.connector_success_rate.collect(),
+ payments_success_rate_distribution,
+ payments_success_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution,
+ payments_failure_rate_distribution_without_smart_retries,
+ failure_reason_count,
+ failure_reason_count_without_smart_retries,
}
}
}
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index f41e1719450..59ae549b283 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -6,8 +6,8 @@ use api_models::analytics::{
MetricsBucketResponse, PaymentDimensions, PaymentDistributions, PaymentMetrics,
PaymentMetricsBucketIdentifier,
},
- AnalyticsMetadata, FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest,
- MetricsResponse, PaymentFiltersResponse,
+ FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse,
+ PaymentsAnalyticsMetadata, PaymentsMetricsResponse,
};
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
@@ -48,7 +48,7 @@ pub async fn get_metrics(
pool: &AnalyticsProvider,
auth: &AuthInfo,
req: GetPaymentMetricRequest,
-) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
+) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
PaymentMetricsBucketIdentifier,
PaymentMetricsAccumulator,
@@ -137,32 +137,47 @@ pub async fn get_metrics(
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
- PaymentMetrics::PaymentSuccessRate => metrics_builder
+ PaymentMetrics::PaymentSuccessRate
+ | PaymentMetrics::SessionizedPaymentSuccessRate => metrics_builder
.payment_success_rate
.add_metrics_bucket(&value),
- PaymentMetrics::PaymentCount => {
+ PaymentMetrics::PaymentCount | PaymentMetrics::SessionizedPaymentCount => {
metrics_builder.payment_count.add_metrics_bucket(&value)
}
- PaymentMetrics::PaymentSuccessCount => {
+ PaymentMetrics::PaymentSuccessCount
+ | PaymentMetrics::SessionizedPaymentSuccessCount => {
metrics_builder.payment_success.add_metrics_bucket(&value)
}
- PaymentMetrics::PaymentProcessedAmount => {
+ PaymentMetrics::PaymentProcessedAmount
+ | PaymentMetrics::SessionizedPaymentProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
- PaymentMetrics::AvgTicketSize => {
+ PaymentMetrics::AvgTicketSize
+ | PaymentMetrics::SessionizedAvgTicketSize => {
metrics_builder.avg_ticket_size.add_metrics_bucket(&value)
}
- PaymentMetrics::RetriesCount => {
+ PaymentMetrics::RetriesCount | PaymentMetrics::SessionizedRetriesCount => {
metrics_builder.retries_count.add_metrics_bucket(&value);
metrics_builder
.retries_amount_processed
.add_metrics_bucket(&value)
}
- PaymentMetrics::ConnectorSuccessRate => {
+ PaymentMetrics::ConnectorSuccessRate
+ | PaymentMetrics::SessionizedConnectorSuccessRate => {
metrics_builder
.connector_success_rate
.add_metrics_bucket(&value);
}
+ PaymentMetrics::PaymentsDistribution => {
+ metrics_builder
+ .payments_distribution
+ .add_metrics_bucket(&value);
+ }
+ PaymentMetrics::FailureReasons => {
+ metrics_builder
+ .failure_reasons_distribution
+ .add_metrics_bucket(&value);
+ }
}
}
@@ -203,19 +218,56 @@ pub async fn get_metrics(
}
}
}
-
+ let mut total_payment_processed_amount = 0;
+ let mut total_payment_processed_count = 0;
+ let mut total_payment_processed_amount_without_smart_retries = 0;
+ let mut total_payment_processed_count_without_smart_retries = 0;
+ let mut total_failure_reasons_count = 0;
+ let mut total_failure_reasons_count_without_smart_retries = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
- .map(|(id, val)| MetricsBucketResponse {
- values: val.collect(),
- dimensions: id,
+ .map(|(id, val)| {
+ let collected_values = val.collect();
+ if let Some(amount) = collected_values.payment_processed_amount {
+ total_payment_processed_amount += amount;
+ }
+ if let Some(count) = collected_values.payment_processed_count {
+ total_payment_processed_count += count;
+ }
+ if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries {
+ total_payment_processed_amount_without_smart_retries += amount;
+ }
+ if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
+ total_payment_processed_count_without_smart_retries += count;
+ }
+ if let Some(count) = collected_values.failure_reason_count {
+ total_failure_reasons_count += count;
+ }
+ if let Some(count) = collected_values.failure_reason_count_without_smart_retries {
+ total_failure_reasons_count_without_smart_retries += count;
+ }
+ MetricsBucketResponse {
+ values: collected_values,
+ dimensions: id,
+ }
})
.collect();
- Ok(MetricsResponse {
+ Ok(PaymentsMetricsResponse {
query_data,
- meta_data: [AnalyticsMetadata {
- current_time_range: req.time_range,
+ meta_data: [PaymentsAnalyticsMetadata {
+ total_payment_processed_amount: Some(total_payment_processed_amount),
+ total_payment_processed_amount_without_smart_retries: Some(
+ total_payment_processed_amount_without_smart_retries,
+ ),
+ total_payment_processed_count: Some(total_payment_processed_count),
+ total_payment_processed_count_without_smart_retries: Some(
+ total_payment_processed_count_without_smart_retries,
+ ),
+ total_failure_reasons_count: Some(total_failure_reasons_count),
+ total_failure_reasons_count_without_smart_retries: Some(
+ total_failure_reasons_count_without_smart_retries,
+ ),
}],
})
}
@@ -297,6 +349,10 @@ pub async fn get_filters(
PaymentDimensions::ClientVersion => fil.client_version,
PaymentDimensions::ProfileId => fil.profile_id,
PaymentDimensions::CardNetwork => fil.card_network,
+ PaymentDimensions::MerchantId => fil.merchant_id,
+ PaymentDimensions::CardLast4 => fil.card_last_4,
+ PaymentDimensions::CardIssuer => fil.card_issuer,
+ PaymentDimensions::ErrorReason => fil.error_reason,
})
.collect::<Vec<String>>();
res.query_data.push(FilterValue {
diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs
index 3bd8e5f7815..213b6244574 100644
--- a/crates/analytics/src/payments/distribution.rs
+++ b/crates/analytics/src/payments/distribution.rs
@@ -28,6 +28,12 @@ pub struct PaymentDistributionRow {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
+ pub first_attempt: Option<bool>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
pub error_message: Option<String>,
diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs
index 087ec5a640e..241754ee041 100644
--- a/crates/analytics/src/payments/distribution/payment_error_message.rs
+++ b/crates/analytics/src/payments/distribution/payment_error_message.rs
@@ -155,6 +155,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs
index 094fd574169..51805acaae2 100644
--- a/crates/analytics/src/payments/filters.rs
+++ b/crates/analytics/src/payments/filters.rs
@@ -60,4 +60,8 @@ pub struct PaymentFilterRow {
pub client_version: Option<String>,
pub profile_id: Option<String>,
pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
}
diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs
index 731f03a247a..23b133ad035 100644
--- a/crates/analytics/src/payments/metrics.rs
+++ b/crates/analytics/src/payments/metrics.rs
@@ -19,6 +19,7 @@ mod payment_count;
mod payment_processed_amount;
mod payment_success_count;
mod retries_count;
+mod sessionized_metrics;
mod success_rate;
use avg_ticket_size::AvgTicketSize;
@@ -41,6 +42,12 @@ pub struct PaymentMetricRow {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
+ pub first_attempt: Option<bool>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
@@ -122,6 +129,51 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::SessionizedPaymentSuccessRate => {
+ sessionized_metrics::PaymentSuccessRate
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentCount => {
+ sessionized_metrics::PaymentCount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentSuccessCount => {
+ sessionized_metrics::PaymentSuccessCount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedPaymentProcessedAmount => {
+ sessionized_metrics::PaymentProcessedAmount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedAvgTicketSize => {
+ sessionized_metrics::AvgTicketSize
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRetriesCount => {
+ sessionized_metrics::RetriesCount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedConnectorSuccessRate => {
+ sessionized_metrics::ConnectorSuccessRate
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::PaymentsDistribution => {
+ sessionized_metrics::PaymentsDistribution
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::FailureReasons => {
+ sessionized_metrics::FailureReasons
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs
index ec76bfc86dc..fc2f44cada2 100644
--- a/crates/analytics/src/payments/metrics/avg_ticket_size.rs
+++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs
@@ -117,6 +117,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs
index e44e87a7e5f..36783eda72a 100644
--- a/crates/analytics/src/payments/metrics/connector_success_rate.rs
+++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs
@@ -112,6 +112,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs
index 642ba9ef035..bd0b52d7cf8 100644
--- a/crates/analytics/src/payments/metrics/payment_count.rs
+++ b/crates/analytics/src/payments/metrics/payment_count.rs
@@ -103,6 +103,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
index c31b8873cb8..b8b3868803c 100644
--- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs
+++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
@@ -111,6 +111,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs
index a45a4557c52..ea926761c13 100644
--- a/crates/analytics/src/payments/metrics/payment_success_count.rs
+++ b/crates/analytics/src/payments/metrics/payment_success_count.rs
@@ -110,6 +110,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs
index c3c7d40e321..9695e1fe18b 100644
--- a/crates/analytics/src/payments/metrics/retries_count.rs
+++ b/crates/analytics/src/payments/metrics/retries_count.rs
@@ -107,6 +107,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs
new file mode 100644
index 00000000000..b7f13667917
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs
@@ -0,0 +1,146 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::{PaymentMetric, PaymentMetricRow};
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct AvgTicketSize;
+
+#[async_trait::async_trait]
+impl<T> PaymentMetric<T> for AvgTicketSize
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ PaymentDimensions::PaymentStatus,
+ storage_enums::AttemptStatus::Charged,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.status.as_ref().map(|i| i.0),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs
new file mode 100644
index 00000000000..66006c15a2a
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs
@@ -0,0 +1,141 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
+ Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct ConnectorSuccessRate;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for ConnectorSuccessRate
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentDimensions::PaymentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_custom_filter_clause(PaymentDimensions::Connector, "NULL", FilterTypes::IsNotNull)
+ .switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
new file mode 100644
index 00000000000..70ae64e0115
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
@@ -0,0 +1,208 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket,
+ ToSql, Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct FailureReasons;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for FailureReasons
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut inner_query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+ inner_query_builder
+ .add_select_column("sum(sign_flag)")
+ .switch()?;
+
+ inner_query_builder
+ .add_custom_filter_clause(
+ PaymentDimensions::ErrorReason,
+ "NULL",
+ FilterTypes::IsNotNull,
+ )
+ .switch()?;
+
+ time_range
+ .set_filter_clause(&mut inner_query_builder)
+ .attach_printable("Error filtering time range for inner query")
+ .switch()?;
+
+ let inner_query_string = inner_query_builder
+ .build_query()
+ .attach_printable("Error building inner query")
+ .change_context(MetricsError::QueryBuildingError)?;
+
+ let mut outer_query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ for dim in dimensions.iter() {
+ outer_query_builder.add_select_column(dim).switch()?;
+ }
+
+ outer_query_builder
+ .add_select_column("sum(sign_flag) AS count")
+ .switch()?;
+
+ outer_query_builder
+ .add_select_column(format!("({}) AS total", inner_query_string))
+ .switch()?;
+
+ outer_query_builder
+ .add_select_column("first_attempt")
+ .switch()?;
+
+ outer_query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+
+ outer_query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters
+ .set_filter_clause(&mut outer_query_builder)
+ .switch()?;
+
+ auth.set_filter_clause(&mut outer_query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut outer_query_builder)
+ .attach_printable("Error filtering time range for outer query")
+ .switch()?;
+
+ outer_query_builder
+ .add_filter_clause(
+ PaymentDimensions::PaymentStatus,
+ storage_enums::AttemptStatus::Failure,
+ )
+ .switch()?;
+
+ outer_query_builder
+ .add_custom_filter_clause(
+ PaymentDimensions::ErrorReason,
+ "NULL",
+ FilterTypes::IsNotNull,
+ )
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ outer_query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ outer_query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut outer_query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ outer_query_builder
+ .add_order_by_clause("count", Order::Descending)
+ .attach_printable("Error adding order by clause")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ if dim != &PaymentDimensions::ErrorReason {
+ outer_query_builder
+ .add_order_by_clause(dim, Order::Ascending)
+ .attach_printable("Error adding order by clause")
+ .switch()?;
+ }
+ }
+
+ outer_query_builder
+ .set_limit_by(5, &[PaymentDimensions::Connector])
+ .attach_printable("Error adding limit clause")
+ .switch()?;
+
+ outer_query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs
new file mode 100644
index 00000000000..e3a5e370534
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs
@@ -0,0 +1,20 @@
+mod avg_ticket_size;
+mod connector_success_rate;
+mod failure_reasons;
+mod payment_count;
+mod payment_processed_amount;
+mod payment_success_count;
+mod payments_distribution;
+mod retries_count;
+mod success_rate;
+pub(super) use avg_ticket_size::AvgTicketSize;
+pub(super) use connector_success_rate::ConnectorSuccessRate;
+pub(super) use failure_reasons::FailureReasons;
+pub(super) use payment_count::PaymentCount;
+pub(super) use payment_processed_amount::PaymentProcessedAmount;
+pub(super) use payment_success_count::PaymentSuccessCount;
+pub(super) use payments_distribution::PaymentsDistribution;
+pub(super) use retries_count::RetriesCount;
+pub(super) use success_rate::PaymentSuccessRate;
+
+pub use super::{PaymentMetric, PaymentMetricAnalytics, PaymentMetricRow};
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs
new file mode 100644
index 00000000000..29d083dd232
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs
@@ -0,0 +1,129 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentCount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for PaymentCount
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.status.as_ref().map(|i| i.0),
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs
new file mode 100644
index 00000000000..9bc554eaae7
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs
@@ -0,0 +1,155 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentProcessedAmount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for PaymentProcessedAmount
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentDimensions::PaymentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder.add_select_column("first_attempt").switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ PaymentDimensions::PaymentStatus,
+ storage_enums::AttemptStatus::Charged,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs
new file mode 100644
index 00000000000..b307b77d5da
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs
@@ -0,0 +1,139 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentSuccessCount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for PaymentSuccessCount
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ PaymentDimensions::PaymentStatus,
+ storage_enums::AttemptStatus::Charged,
+ )
+ .switch()?;
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs
new file mode 100644
index 00000000000..e0987dd0d22
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs
@@ -0,0 +1,142 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentsDistribution;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for PaymentsDistribution
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentDimensions::PaymentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+
+ query_builder.add_select_column("first_attempt").switch()?;
+
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+ query_builder
+ .add_group_by_clause("first_attempt")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs
new file mode 100644
index 00000000000..b79489744cc
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs
@@ -0,0 +1,135 @@
+use std::collections::HashSet;
+
+use api_models::{
+ analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+ },
+ enums::IntentStatus,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
+ Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RetriesCount;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for RetriesCount
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ _dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ _filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
+ .switch()?;
+ query_builder
+ .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
+ .switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs
new file mode 100644
index 00000000000..30e7471d608
--- /dev/null
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs
@@ -0,0 +1,135 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::PaymentMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct PaymentSuccessRate;
+
+#[async_trait::async_trait]
+impl<T> super::PaymentMetric<T> for PaymentSuccessRate
+where
+ T: AnalyticsDataSource + super::PaymentMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[PaymentDimensions],
+ auth: &AuthInfo,
+ filters: &PaymentFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::PaymentSessionized);
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(PaymentDimensions::PaymentStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ auth.set_filter_clause(&mut query_builder).switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<PaymentMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ PaymentMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.authentication_type.as_ref().map(|i| i.0),
+ i.payment_method.clone(),
+ i.payment_method_type.clone(),
+ i.client_source.clone(),
+ i.client_version.clone(),
+ i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs
index b8e840c2203..e756115a67d 100644
--- a/crates/analytics/src/payments/metrics/success_rate.rs
+++ b/crates/analytics/src/payments/metrics/success_rate.rs
@@ -106,6 +106,11 @@ where
i.client_source.clone(),
i.client_version.clone(),
i.profile_id.clone(),
+ i.card_network.clone(),
+ i.merchant_id.clone(),
+ i.card_last_4.clone(),
+ i.card_issuer.clone(),
+ i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs
index b7984a19ea3..e23fc6cbbb3 100644
--- a/crates/analytics/src/payments/types.rs
+++ b/crates/analytics/src/payments/types.rs
@@ -48,7 +48,7 @@ where
PaymentDimensions::PaymentMethodType,
&self.payment_method_type,
)
- .attach_printable("Error adding payment method filter")?;
+ .attach_printable("Error adding payment method type filter")?;
}
if !self.client_source.is_empty() {
builder
@@ -84,6 +84,26 @@ where
)
.attach_printable("Error adding card network filter")?;
}
+ if !self.merchant_id.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentDimensions::MerchantId, &self.merchant_id)
+ .attach_printable("Error adding merchant id filter")?;
+ }
+ if !self.card_last_4.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentDimensions::CardLast4, &self.card_last_4)
+ .attach_printable("Error adding card last 4 filter")?;
+ }
+ if !self.card_issuer.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentDimensions::CardIssuer, &self.card_issuer)
+ .attach_printable("Error adding card issuer filter")?;
+ }
+ if !self.error_reason.is_empty() {
+ builder
+ .add_filter_in_range_clause(PaymentDimensions::ErrorReason, &self.error_reason)
+ .attach_printable("Error adding error reason filter")?;
+ }
Ok(())
}
}
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index 5f8a2f4a330..7ce338f7db3 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -1,4 +1,4 @@
-use std::marker::PhantomData;
+use std::{fmt, marker::PhantomData};
use api_models::{
analytics::{
@@ -301,8 +301,8 @@ pub enum Order {
Descending,
}
-impl std::fmt::Display for Order {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+impl fmt::Display for Order {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Ascending => write!(f, "asc"),
Self::Descending => write!(f, "desc"),
@@ -335,6 +335,68 @@ pub struct TopN {
pub order: Order,
}
+#[derive(Debug, Clone)]
+pub struct LimitByClause {
+ limit: u64,
+ columns: Vec<String>,
+}
+
+impl fmt::Display for LimitByClause {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "LIMIT {} BY {}", self.limit, self.columns.join(", "))
+ }
+}
+
+#[derive(Debug, Default, Clone, Copy)]
+pub enum FilterCombinator {
+ #[default]
+ And,
+ Or,
+}
+
+impl<T: AnalyticsDataSource> ToSql<T> for FilterCombinator {
+ fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
+ Ok(match self {
+ Self::And => " AND ",
+ Self::Or => " OR ",
+ }
+ .to_owned())
+ }
+}
+
+#[derive(Debug, Clone)]
+pub enum Filter {
+ Plain(String, FilterTypes, String),
+ NestedFilter(FilterCombinator, Vec<Filter>),
+}
+
+impl Default for Filter {
+ fn default() -> Self {
+ Self::NestedFilter(FilterCombinator::default(), Vec::new())
+ }
+}
+
+impl<T: AnalyticsDataSource> ToSql<T> for Filter {
+ fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
+ Ok(match self {
+ Self::Plain(l, op, r) => filter_type_to_sql(l, op, r),
+ Self::NestedFilter(operator, filters) => {
+ format!(
+ "( {} )",
+ filters
+ .iter()
+ .map(|f| <Self as ToSql<T>>::to_sql(f, table_engine))
+ .collect::<Result<Vec<String>, _>>()?
+ .join(
+ <FilterCombinator as ToSql<T>>::to_sql(operator, table_engine)?
+ .as_ref()
+ )
+ )
+ }
+ })
+ }
+}
+
#[derive(Debug)]
pub struct QueryBuilder<T>
where
@@ -342,9 +404,11 @@ where
AnalyticsCollection: ToSql<T>,
{
columns: Vec<String>,
- filters: Vec<(String, FilterTypes, String)>,
+ filters: Filter,
group_by: Vec<String>,
+ order_by: Vec<String>,
having: Option<Vec<(String, FilterTypes, String)>>,
+ limit_by: Option<LimitByClause>,
outer_select: Vec<String>,
top_n: Option<TopN>,
table: AnalyticsCollection,
@@ -444,7 +508,7 @@ impl_to_sql_for_to_string!(
DisputeStage
);
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub enum FilterTypes {
Equal,
NotEqual,
@@ -483,7 +547,9 @@ where
columns: Default::default(),
filters: Default::default(),
group_by: Default::default(),
+ order_by: Default::default(),
having: Default::default(),
+ limit_by: Default::default(),
outer_select: Default::default(),
top_n: Default::default(),
table,
@@ -580,7 +646,7 @@ where
rhs: impl ToSql<T>,
comparison: FilterTypes,
) -> QueryResult<()> {
- self.filters.push((
+ let filter = Filter::Plain(
lhs.to_sql(&self.table_engine)
.change_context(QueryBuildingError::SqlSerializeError)
.attach_printable("Error serializing filter key")?,
@@ -588,9 +654,18 @@ where
rhs.to_sql(&self.table_engine)
.change_context(QueryBuildingError::SqlSerializeError)
.attach_printable("Error serializing filter value")?,
- ));
+ );
+ self.add_nested_filter_clause(filter);
Ok(())
}
+ pub fn add_nested_filter_clause(&mut self, filter: Filter) {
+ match &mut self.filters {
+ Filter::NestedFilter(_, ref mut filters) => filters.push(filter),
+ f @ Filter::Plain(_, _, _) => {
+ self.filters = Filter::NestedFilter(FilterCombinator::And, vec![f.clone(), filter]);
+ }
+ }
+ }
pub fn add_filter_in_range_clause(
&mut self,
@@ -623,6 +698,37 @@ where
Ok(())
}
+ pub fn add_order_by_clause(
+ &mut self,
+ column: impl ToSql<T>,
+ order: impl ToSql<T>,
+ ) -> QueryResult<()> {
+ let column_sql = column
+ .to_sql(&self.table_engine)
+ .change_context(QueryBuildingError::SqlSerializeError)
+ .attach_printable("Error serializing order by column")?;
+
+ let order_sql = order
+ .to_sql(&self.table_engine)
+ .change_context(QueryBuildingError::SqlSerializeError)
+ .attach_printable("Error serializing order direction")?;
+
+ self.order_by.push(format!("{} {}", column_sql, order_sql));
+ Ok(())
+ }
+
+ pub fn set_limit_by(&mut self, limit: u64, columns: &[impl ToSql<T>]) -> QueryResult<()> {
+ let columns = columns
+ .iter()
+ .map(|col| col.to_sql(&self.table_engine))
+ .collect::<Result<Vec<String>, _>>()
+ .change_context(QueryBuildingError::SqlSerializeError)
+ .attach_printable("Error serializing LIMIT BY columns")?;
+
+ self.limit_by = Some(LimitByClause { limit, columns });
+ Ok(())
+ }
+
pub fn add_granularity_in_mins(&mut self, granularity: &Granularity) -> QueryResult<()> {
let interval = match granularity {
Granularity::OneMin => "1",
@@ -638,12 +744,9 @@ where
Ok(())
}
- fn get_filter_clause(&self) -> String {
- self.filters
- .iter()
- .map(|(l, op, r)| filter_type_to_sql(l, op, r))
- .collect::<Vec<String>>()
- .join(" AND ")
+ fn get_filter_clause(&self) -> QueryResult<String> {
+ <Filter as ToSql<T>>::to_sql(&self.filters, &self.table_engine)
+ .change_context(QueryBuildingError::SqlSerializeError)
}
fn get_select_clause(&self) -> String {
@@ -731,9 +834,10 @@ where
.attach_printable("Error serializing table value")?,
);
- if !self.filters.is_empty() {
+ let filter_clause = self.get_filter_clause()?;
+ if !filter_clause.is_empty() {
query.push_str(" WHERE ");
- query.push_str(&self.get_filter_clause());
+ query.push_str(filter_clause.as_str());
}
if !self.group_by.is_empty() {
@@ -758,6 +862,15 @@ where
}
}
+ if !self.order_by.is_empty() {
+ query.push_str(" ORDER BY ");
+ query.push_str(&self.order_by.join(", "));
+ }
+
+ if let Some(limit_by) = &self.limit_by {
+ query.push_str(&format!(" {}", limit_by));
+ }
+
if !self.outer_select.is_empty() {
query.insert_str(
0,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index e9395439209..ae72bbeffea 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -330,6 +330,30 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -355,6 +379,12 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {
client_source,
client_version,
profile_id,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
+ first_attempt,
total,
count,
start_bucket,
@@ -407,6 +437,26 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -419,6 +469,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
@@ -436,6 +490,12 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi
client_source,
client_version,
profile_id,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
+ first_attempt,
total,
count,
error_message,
@@ -493,6 +553,22 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
Ok(Self {
currency,
status,
@@ -504,6 +580,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
client_version,
profile_id,
card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
})
}
}
@@ -524,6 +604,45 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
+ row.try_get("authentication_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let payment_method: Option<String> =
+ row.try_get("payment_method").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let payment_method_type: Option<String> =
+ row.try_get("payment_method_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -532,6 +651,10 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let first_attempt: Option<i64> = row.try_get("first_attempt").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
// Removing millisecond precision to get accurate diffs against clickhouse
let start_bucket: Option<PrimitiveDateTime> = row
.try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
@@ -543,6 +666,16 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe
status,
currency,
profile_id,
+ connector,
+ authentication_type,
+ payment_method,
+ payment_method_type,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
+ first_attempt,
total,
count,
start_bucket,
@@ -567,11 +700,58 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
-
+ let connector: Option<String> = row.try_get("connector").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let authentication_type: Option<DBEnumWrapper<AuthenticationType>> =
+ row.try_get("authentication_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let payment_method: Option<String> =
+ row.try_get("payment_method").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let payment_method_type: Option<String> =
+ row.try_get("payment_method_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
Ok(Self {
status,
currency,
profile_id,
+ connector,
+ authentication_type,
+ payment_method,
+ payment_method_type,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
})
}
}
@@ -716,7 +896,11 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
match self {
Self::Payment => Ok("payment_attempt".to_string()),
+ Self::PaymentSessionized => Err(error_stack::report!(ParsingError::UnknownError)
+ .attach_printable("PaymentSessionized table is not implemented for Sqlx"))?,
Self::Refund => Ok("refund".to_string()),
+ Self::RefundSessionized => Err(error_stack::report!(ParsingError::UnknownError)
+ .attach_printable("RefundSessionized table is not implemented for Sqlx"))?,
Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?,
Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
@@ -725,6 +909,10 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
Self::FraudCheck => Ok("fraud_check".to_string()),
Self::PaymentIntent => Ok("payment_intent".to_string()),
+ Self::PaymentIntentSessionized => Err(error_stack::report!(
+ ParsingError::UnknownError
+ )
+ .attach_printable("PaymentIntentSessionized table is not implemented for Sqlx"))?,
Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ConnectorEvents table is not implemented for Sqlx"))?,
Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError)
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 6593e5d6eb0..6bdd11fcd73 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -26,12 +26,15 @@ pub enum AnalyticsDomain {
#[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)]
pub enum AnalyticsCollection {
Payment,
+ PaymentSessionized,
Refund,
+ RefundSessionized,
FraudCheck,
SdkEvents,
SdkEventsAnalytics,
ApiEvents,
PaymentIntent,
+ PaymentIntentSessionized,
ConnectorEvents,
OutgoingWebhookEvent,
Dispute,
@@ -56,6 +59,12 @@ impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> {
}
}
+impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> {
+ fn default() -> Self {
+ Self(T::default())
+ }
+}
+
impl<T> FromStr for DBEnumWrapper<T>
where
T: FromStr + Display,
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index 7b73f5a1c1d..fc21bf09819 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -12,11 +12,39 @@ use api_models::analytics::{
use strum::IntoEnumIterator;
pub fn get_payment_dimensions() -> Vec<NameDescription> {
- PaymentDimensions::iter().map(Into::into).collect()
+ vec![
+ PaymentDimensions::Connector,
+ PaymentDimensions::PaymentMethod,
+ PaymentDimensions::PaymentMethodType,
+ PaymentDimensions::Currency,
+ PaymentDimensions::AuthType,
+ PaymentDimensions::PaymentStatus,
+ PaymentDimensions::ClientSource,
+ PaymentDimensions::ClientVersion,
+ PaymentDimensions::ProfileId,
+ PaymentDimensions::CardNetwork,
+ PaymentDimensions::MerchantId,
+ ]
+ .into_iter()
+ .map(Into::into)
+ .collect()
}
pub fn get_payment_intent_dimensions() -> Vec<NameDescription> {
- PaymentIntentDimensions::iter().map(Into::into).collect()
+ vec![
+ PaymentIntentDimensions::PaymentIntentStatus,
+ PaymentIntentDimensions::Currency,
+ PaymentIntentDimensions::ProfileId,
+ PaymentIntentDimensions::Connector,
+ PaymentIntentDimensions::AuthType,
+ PaymentIntentDimensions::PaymentMethod,
+ PaymentIntentDimensions::PaymentMethodType,
+ PaymentIntentDimensions::CardNetwork,
+ PaymentIntentDimensions::MerchantId,
+ ]
+ .into_iter()
+ .map(Into::into)
+ .collect()
}
pub fn get_refund_dimensions() -> Vec<NameDescription> {
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 0379ec09547..b95404080b0 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -200,6 +200,28 @@ pub struct AnalyticsMetadata {
pub current_time_range: TimeRange,
}
+#[derive(Debug, serde::Serialize)]
+pub struct PaymentsAnalyticsMetadata {
+ pub total_payment_processed_amount: Option<u64>,
+ pub total_payment_processed_amount_without_smart_retries: Option<u64>,
+ pub total_payment_processed_count: Option<u64>,
+ pub total_payment_processed_count_without_smart_retries: Option<u64>,
+ pub total_failure_reasons_count: Option<u64>,
+ pub total_failure_reasons_count_without_smart_retries: Option<u64>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct PaymentIntentsAnalyticsMetadata {
+ pub total_success_rate: Option<f64>,
+ pub total_success_rate_without_smart_retries: Option<f64>,
+ pub total_smart_retried_amount: Option<u64>,
+ pub total_smart_retried_amount_without_smart_retries: Option<u64>,
+ pub total_payment_processed_amount: Option<u64>,
+ pub total_payment_processed_amount_without_smart_retries: Option<u64>,
+ pub total_payment_processed_count: Option<u64>,
+ pub total_payment_processed_count_without_smart_retries: Option<u64>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentFiltersRequest {
@@ -320,6 +342,20 @@ pub struct MetricsResponse<T> {
pub meta_data: [AnalyticsMetadata; 1],
}
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentsMetricsResponse<T> {
+ pub query_data: Vec<T>,
+ pub meta_data: [PaymentsAnalyticsMetadata; 1],
+}
+
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentIntentsMetricsResponse<T> {
+ pub query_data: Vec<T>,
+ pub meta_data: [PaymentIntentsAnalyticsMetadata; 1],
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
@@ -390,3 +426,21 @@ pub struct GetDisputeMetricRequest {
#[serde(default)]
pub delta: bool,
}
+
+#[derive(Clone, Debug, Default, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SankeyResponse {
+ pub normal_success: i64,
+ pub normal_failure: i64,
+ pub cancelled: i64,
+ pub smart_retried_success: i64,
+ pub smart_retried_failure: i64,
+ pub pending: i64,
+ pub partial_refunded: i64,
+ pub refunded: i64,
+ pub disputed: i64,
+ pub pm_awaited: i64,
+ pub customer_awaited: i64,
+ pub merchant_awaited: i64,
+ pub confirmation_awaited: i64,
+}
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 61e336185b6..41f11c19ef8 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -6,7 +6,9 @@ use std::{
use common_utils::id_type;
use super::{NameDescription, TimeRange};
-use crate::enums::{Currency, IntentStatus};
+use crate::enums::{
+ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
+};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentIntentFilters {
@@ -16,6 +18,24 @@ pub struct PaymentIntentFilters {
pub currency: Vec<Currency>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
+ #[serde(default)]
+ pub connector: Vec<Connector>,
+ #[serde(default)]
+ pub auth_type: Vec<AuthenticationType>,
+ #[serde(default)]
+ pub payment_method: Vec<PaymentMethod>,
+ #[serde(default)]
+ pub payment_method_type: Vec<PaymentMethodType>,
+ #[serde(default)]
+ pub card_network: Vec<String>,
+ #[serde(default)]
+ pub merchant_id: Vec<id_type::MerchantId>,
+ #[serde(default)]
+ pub card_last_4: Vec<String>,
+ #[serde(default)]
+ pub card_issuer: Vec<String>,
+ #[serde(default)]
+ pub error_reason: Vec<String>,
}
#[derive(
@@ -40,6 +60,15 @@ pub enum PaymentIntentDimensions {
PaymentIntentStatus,
Currency,
ProfileId,
+ Connector,
+ AuthType,
+ PaymentMethod,
+ PaymentMethodType,
+ CardNetwork,
+ MerchantId,
+ CardLast4,
+ CardIssuer,
+ ErrorReason,
}
#[derive(
@@ -61,6 +90,14 @@ pub enum PaymentIntentMetrics {
TotalSmartRetries,
SmartRetriedAmount,
PaymentIntentCount,
+ PaymentsSuccessRate,
+ SessionizedSuccessfulSmartRetries,
+ SessionizedTotalSmartRetries,
+ SessionizedSmartRetriedAmount,
+ SessionizedPaymentIntentCount,
+ SessionizedPaymentsSuccessRate,
+ SessionizedPaymentProcessedAmount,
+ SessionizedPaymentsDistribution,
}
#[derive(Debug, Default, serde::Serialize)]
@@ -75,6 +112,7 @@ pub mod metric_behaviour {
pub struct TotalSmartRetries;
pub struct SmartRetriedAmount;
pub struct PaymentIntentCount;
+ pub struct PaymentsSuccessRate;
}
impl From<PaymentIntentMetrics> for NameDescription {
@@ -100,6 +138,15 @@ pub struct PaymentIntentMetricsBucketIdentifier {
pub status: Option<IntentStatus>,
pub currency: Option<Currency>,
pub profile_id: Option<String>,
+ pub connector: Option<String>,
+ pub auth_type: Option<AuthenticationType>,
+ pub payment_method: Option<String>,
+ pub payment_method_type: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
@@ -113,12 +160,30 @@ impl PaymentIntentMetricsBucketIdentifier {
status: Option<IntentStatus>,
currency: Option<Currency>,
profile_id: Option<String>,
+ connector: Option<String>,
+ auth_type: Option<AuthenticationType>,
+ payment_method: Option<String>,
+ payment_method_type: Option<String>,
+ card_network: Option<String>,
+ merchant_id: Option<String>,
+ card_last_4: Option<String>,
+ card_issuer: Option<String>,
+ error_reason: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
status,
currency,
profile_id,
+ connector,
+ auth_type,
+ payment_method,
+ payment_method_type,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
@@ -130,6 +195,15 @@ impl Hash for PaymentIntentMetricsBucketIdentifier {
self.status.map(|i| i.to_string()).hash(state);
self.currency.hash(state);
self.profile_id.hash(state);
+ self.connector.hash(state);
+ self.auth_type.map(|i| i.to_string()).hash(state);
+ self.payment_method.hash(state);
+ self.payment_method_type.hash(state);
+ self.card_network.hash(state);
+ self.merchant_id.hash(state);
+ self.card_last_4.hash(state);
+ self.card_issuer.hash(state);
+ self.error_reason.hash(state);
self.time_bucket.hash(state);
}
}
@@ -149,7 +223,19 @@ pub struct PaymentIntentMetricsBucketValue {
pub successful_smart_retries: Option<u64>,
pub total_smart_retries: Option<u64>,
pub smart_retried_amount: Option<u64>,
+ pub smart_retried_amount_without_smart_retries: Option<u64>,
pub payment_intent_count: Option<u64>,
+ pub successful_payments: Option<u32>,
+ pub successful_payments_without_smart_retries: Option<u32>,
+ pub total_payments: Option<u32>,
+ pub payments_success_rate: Option<f64>,
+ pub payments_success_rate_without_smart_retries: Option<f64>,
+ pub payment_processed_amount: Option<u64>,
+ pub payment_processed_count: Option<u64>,
+ pub payment_processed_amount_without_smart_retries: Option<u64>,
+ pub payment_processed_count_without_smart_retries: Option<u64>,
+ pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
+ pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index c474d47ee63..1120ab092d7 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -33,6 +33,14 @@ pub struct PaymentFilters {
pub card_network: Vec<CardNetwork>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
+ #[serde(default)]
+ pub merchant_id: Vec<id_type::MerchantId>,
+ #[serde(default)]
+ pub card_last_4: Vec<String>,
+ #[serde(default)]
+ pub card_issuer: Vec<String>,
+ #[serde(default)]
+ pub error_reason: Vec<String>,
}
#[derive(
@@ -68,6 +76,12 @@ pub enum PaymentDimensions {
ClientVersion,
ProfileId,
CardNetwork,
+ MerchantId,
+ #[strum(serialize = "card_last_4")]
+ #[serde(rename = "card_last_4")]
+ CardLast4,
+ CardIssuer,
+ ErrorReason,
}
#[derive(
@@ -92,6 +106,15 @@ pub enum PaymentMetrics {
AvgTicketSize,
RetriesCount,
ConnectorSuccessRate,
+ SessionizedPaymentSuccessRate,
+ SessionizedPaymentCount,
+ SessionizedPaymentSuccessCount,
+ SessionizedPaymentProcessedAmount,
+ SessionizedAvgTicketSize,
+ SessionizedRetriesCount,
+ SessionizedConnectorSuccessRate,
+ PaymentsDistribution,
+ FailureReasons,
}
#[derive(Debug, Default, serde::Serialize)]
@@ -159,6 +182,11 @@ pub struct PaymentMetricsBucketIdentifier {
pub client_source: Option<String>,
pub client_version: Option<String>,
pub profile_id: Option<String>,
+ pub card_network: Option<String>,
+ pub merchant_id: Option<String>,
+ pub card_last_4: Option<String>,
+ pub card_issuer: Option<String>,
+ pub error_reason: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
// Coz FE sucks
@@ -179,6 +207,11 @@ impl PaymentMetricsBucketIdentifier {
client_source: Option<String>,
client_version: Option<String>,
profile_id: Option<String>,
+ card_network: Option<String>,
+ merchant_id: Option<String>,
+ card_last_4: Option<String>,
+ card_issuer: Option<String>,
+ error_reason: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
@@ -191,6 +224,11 @@ impl PaymentMetricsBucketIdentifier {
client_source,
client_version,
profile_id,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
@@ -208,6 +246,11 @@ impl Hash for PaymentMetricsBucketIdentifier {
self.client_source.hash(state);
self.client_version.hash(state);
self.profile_id.hash(state);
+ self.card_network.hash(state);
+ self.merchant_id.hash(state);
+ self.card_last_4.hash(state);
+ self.card_issuer.hash(state);
+ self.error_reason.hash(state);
self.time_bucket.hash(state);
}
}
@@ -228,11 +271,20 @@ pub struct PaymentMetricsBucketValue {
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
+ pub payment_processed_count: Option<u64>,
+ pub payment_processed_amount_without_smart_retries: Option<u64>,
+ pub payment_processed_count_without_smart_retries: Option<u64>,
pub avg_ticket_size: Option<f64>,
pub payment_error_message: Option<Vec<ErrorResult>>,
pub retries_count: Option<u64>,
pub retries_amount_processed: Option<u64>,
pub connector_success_rate: Option<f64>,
+ pub payments_success_rate_distribution: Option<f64>,
+ pub payments_success_rate_distribution_without_smart_retries: Option<f64>,
+ pub payments_failure_rate_distribution: Option<f64>,
+ pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
+ pub failure_reason_count: Option<u64>,
+ pub failure_reason_count_without_smart_retries: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 5816df518bd..7272abffbff 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -131,6 +131,7 @@ impl_api_event_type!(
GetDisputeFilterRequest,
DisputeFiltersResponse,
GetDisputeMetricRequest,
+ SankeyResponse,
OrganizationResponse,
OrganizationCreateRequest,
OrganizationUpdateRequest,
@@ -155,6 +156,18 @@ impl<T> ApiEventMetric for MetricsResponse<T> {
}
}
+impl<T> ApiEventMetric for PaymentsMetricsResponse<T> {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Miscellaneous)
+ }
+}
+
+impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Miscellaneous)
+ }
+}
+
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl ApiEventMetric for PaymentMethodIntentConfirmInternal {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 89159bcff86..aa6db56bb34 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -26,6 +26,7 @@ pub mod routes {
GetSdkEventMetricRequest, ReportRequest,
};
use common_enums::EntityType;
+ use common_utils::types::TimeRange;
use error_stack::{report, ResultExt};
use futures::{stream::FuturesUnordered, StreamExt};
@@ -142,6 +143,10 @@ pub mod routes {
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
)
+ .service(
+ web::resource("metrics/sankey")
+ .route(web::post().to(get_merchant_sankey)),
+ )
.service(
web::scope("/merchant")
.service(
@@ -190,6 +195,10 @@ pub mod routes {
.service(
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
+ )
+ .service(
+ web::resource("metrics/sankey")
+ .route(web::post().to(get_merchant_sankey)),
),
)
.service(
@@ -232,6 +241,10 @@ pub mod routes {
.service(
web::resource("report/payments")
.route(web::post().to(generate_org_payment_report)),
+ )
+ .service(
+ web::resource("metrics/sankey")
+ .route(web::post().to(get_org_sankey)),
),
)
.service(
@@ -290,6 +303,10 @@ pub mod routes {
.service(
web::resource("sdk_event_logs")
.route(web::post().to(get_profile_sdk_events)),
+ )
+ .service(
+ web::resource("metrics/sankey")
+ .route(web::post().to(get_profile_sankey)),
),
),
)
@@ -2277,4 +2294,103 @@ pub mod routes {
))
.await
}
+
+ pub async fn get_merchant_sankey(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<TimeRange>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetSankey;
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req, _| async move {
+ let org_id = auth.merchant_account.get_org_id();
+ let merchant_id = auth.merchant_account.get_id();
+ let auth: AuthInfo = AuthInfo::MerchantLevel {
+ org_id: org_id.clone(),
+ merchant_ids: vec![merchant_id.clone()],
+ };
+ analytics::payment_intents::get_sankey(&state.pool, &auth, req)
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
+ pub async fn get_org_sankey(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<TimeRange>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetSankey;
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req, _| async move {
+ let org_id = auth.merchant_account.get_org_id();
+ let auth: AuthInfo = AuthInfo::OrgLevel {
+ org_id: org_id.clone(),
+ };
+ analytics::payment_intents::get_sankey(&state.pool, &auth, req)
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Organization,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
+ pub async fn get_profile_sankey(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<TimeRange>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetSankey;
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move {
+ let org_id = auth.merchant_account.get_org_id();
+ let merchant_id = auth.merchant_account.get_id();
+ let profile_id = auth
+ .profile_id
+ .ok_or(report!(UserErrors::JwtProfileIdMissing))
+ .change_context(AnalyticsError::AccessForbiddenError)?;
+ let auth: AuthInfo = AuthInfo::ProfileLevel {
+ org_id: org_id.clone(),
+ merchant_id: merchant_id.clone(),
+ profile_ids: vec![profile_id.clone()],
+ };
+ analytics::payment_intents::get_sankey(&state.pool, &auth, req)
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Profile,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
| 2024-09-12T08:10:00Z |
## Description
<!-- Describe your changes in detail -->
Adding metrics, filters and APIs for Analytics v2 Dashboard - Payments page
The new Analytics Dashboard will now have the following metrics:
- Sessionizer Payment Intents based Metrics:
- Total Payments Savings - Amount saved via Smart Retries
- Payments Success Rate - Overall successful payment intents divided by total intents
- Payment Lifecycle - Displayed as a Sankey
- Total Payments Processed - Total payments processed amount and count based on all successful intents
- Successful Payments Distribution - Overall successful intents divided by total number of intents based on group by
- Failed Payments Distribution - Overall failed intents divided by total number of intents based on group by
- Sessionizer Payment Attempts based Metrics:
- Total Payments Processed - Total payments processed amount and count based on all successful attempts
- Successful Payments Distribution - Overall successful attempts divided by total number of attempts based on group by
- Failed Payments Distribution - Overall failed attempts divided by total number of attempts based on group by
- Failure Reasons Distribution - Failure Reason count along with ratio of count / total failed attempts based on group by
- Refunds based Metrics:
- Total Refunds Processed - Successful refunds
- Disputes based Metrics:
- All Disputes - Total number of disputes irrespective of status
The following filters have been added:
- Payment Attempts:
- Merchant_id
- Card last 4
- Error Reason
- Card Issuer
- Payment Intents:
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant id
- card_last_4
- error_reason
- card_issuer
New API endpoints for Payments Lifecycle (Sankey) on different levels:
Payments Lifecycle (Sankey) |
-- | --
Org Level | /analytics/v1/org/metrics/sankey
Merchant Level | /analytics/v1/merchant/metrics/sankey
Profile Level | /analytics/v1/profile/metrics/sankey
Separated out the existing payment_attempts and payment_intents based metrics and sessionizer_payment_attempts and sessionizer_payment_intents based metrics to support backwards compatibility
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Enhancing dashboard experience and providing meaningful and important data analytics for the merchants to make informed decisions
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Curls for different metrics (which are newly created or modified):
Payment Attempts based metrics:
- sessionized_payment_processed_amount
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector", "payment_method"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payment_processed_amount": 6540,
"payment_processed_count": 1,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_count_without_smart_retries": null,
```
metaData:
```bash
"total_payment_processed_amount": 117720,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_count": 18,
"total_payment_processed_count_without_smart_retries": 0,
```
- payments_distribution
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"source": "BATCH",
"metrics": [
"payments_distribution"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payments_success_rate_distribution": 75.0,
"payments_failure_rate_distribution": 25.0,
```
- failure_reasons
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector", "error_reason"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"source": "BATCH",
"metrics": [
"failure_reasons"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"connector": "adyen",
"failure_reason_count": 1,
"failure_reason_count_without_smart_retries": 0,
"error_reason": "Test Failure Reason 4",
```
metaData:
```bash
"total_failure_reasons_count": 7,
"total_failure_reasons_count_without_smart_retries": 0
```
Payment Intents based metrics:
- sessionized_smart_retried_amount
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-09-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_smart_retried_amount"
]
}
]'
```
Fields to look out for in the response body
queryData:
```bash
"smart_retried_amount": 6540,
"smart_retried_amount_without_smart_retries": 0,
```
metaData
```bash
"total_smart_retried_amount": 6540,
"total_smart_retried_amount_without_smart_retries": 0
```
- sessionized_payments_success_rate
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-09-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payments_success_rate"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"successful_payments": 7,
"successful_payments_without_smart_retries": 7,
"total_payments": 7,
"payments_success_rate": 100.0,
"payments_success_rate_without_smart_retries": 100.0,
```
metaData:
```bash
"total_success_rate": 88.23529411764706,
"total_success_rate_without_smart_retries": 82.3529411764706,
```
- sessionized_payment_processed_amount
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"groupByNames": [
"connector"
],
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payment_processed_amount": 26160,
"payment_processed_count": 4,
"payment_processed_amount_without_smart_retries": 19620,
"payment_processed_count_without_smart_retries": 3,
```
metaData:
```bash
"total_payment_processed_amount": 26160,
"total_payment_processed_amount_without_smart_retries": 19620,
"total_payment_processed_count": 4,
"total_payment_processed_count_without_smart_retries": 3
```
- sessionized_payments_distribution
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"groupByNames": [
"connector"
],
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payments_distribution"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payments_success_rate_distribution_without_smart_retries": 50.0,
"payments_failure_rate_distribution_without_smart_retries": 16.666666666666668,
``` | b7139483bb4735b7dfaf7e659ab33a16a90af1db |
Curls for different metrics (which are newly created or modified):
Payment Attempts based metrics:
- sessionized_payment_processed_amount
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector", "payment_method"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payment_processed_amount": 6540,
"payment_processed_count": 1,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_count_without_smart_retries": null,
```
metaData:
```bash
"total_payment_processed_amount": 117720,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_count": 18,
"total_payment_processed_count_without_smart_retries": 0,
```
- payments_distribution
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"source": "BATCH",
"metrics": [
"payments_distribution"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payments_success_rate_distribution": 75.0,
"payments_failure_rate_distribution": 25.0,
```
- failure_reasons
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: test_admin' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-01T23:30:00Z"
},
"groupByNames": [
"connector", "error_reason"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"source": "BATCH",
"metrics": [
"failure_reasons"
],
"delta": true
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"connector": "adyen",
"failure_reason_count": 1,
"failure_reason_count_without_smart_retries": 0,
"error_reason": "Test Failure Reason 4",
```
metaData:
```bash
"total_failure_reasons_count": 7,
"total_failure_reasons_count_without_smart_retries": 0
```
Payment Intents based metrics:
- sessionized_smart_retried_amount
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-09-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_smart_retried_amount"
]
}
]'
```
Fields to look out for in the response body
queryData:
```bash
"smart_retried_amount": 6540,
"smart_retried_amount_without_smart_retries": 0,
```
metaData
```bash
"total_smart_retried_amount": 6540,
"total_smart_retried_amount_without_smart_retries": 0
```
- sessionized_payments_success_rate
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-09-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payments_success_rate"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"successful_payments": 7,
"successful_payments_without_smart_retries": 7,
"total_payments": 7,
"payments_success_rate": 100.0,
"payments_success_rate_without_smart_retries": 100.0,
```
metaData:
```bash
"total_success_rate": 88.23529411764706,
"total_success_rate_without_smart_retries": 82.3529411764706,
```
- sessionized_payment_processed_amount
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"groupByNames": [
"connector"
],
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payment_processed_amount": 26160,
"payment_processed_count": 4,
"payment_processed_amount_without_smart_retries": 19620,
"payment_processed_count_without_smart_retries": 3,
```
metaData:
```bash
"total_payment_processed_amount": 26160,
"total_payment_processed_amount_without_smart_retries": 19620,
"total_payment_processed_count": 4,
"total_payment_processed_count_without_smart_retries": 3
```
- sessionized_payments_distribution
```bash
curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-US,en;q=0.9' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStatTimeseries' \
--header 'Referer: http://localhost:9000/' \
--header 'Sec-Fetch-Dest: empty' \
--header 'Sec-Fetch-Mode: cors' \
--header 'Sec-Fetch-Site: same-site' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \
--header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-09-11T00:00:00Z",
"endTime": "2024-10-26T09:22:30Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"groupByNames": [
"connector"
],
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payments_distribution"
]
}
]'
```
Fields to look out for in the response body:
queryData:
```bash
"payments_success_rate_distribution_without_smart_retries": 50.0,
"payments_failure_rate_distribution_without_smart_retries": 16.666666666666668,
```
| [
"crates/analytics/src/clickhouse.rs",
"crates/analytics/src/lib.rs",
"crates/analytics/src/payment_intents.rs",
"crates/analytics/src/payment_intents/accumulator.rs",
"crates/analytics/src/payment_intents/core.rs",
"crates/analytics/src/payment_intents/filters.rs",
"crates/analytics/src/payment_intents/... | |
juspay/hyperswitch | juspay__hyperswitch-5876 | Bug: [BUG] Nix build is broken
### Bug Description
`nix build` is broken as you can see from the CI failure of https://github.com/juspay/hyperswitch/pull/5017
### Expected Behavior
All outputs of `flake.nix` should build.
### Actual Behavior
Some outputs (eg: router) do not build
### Steps To Reproduce
`nix --accept-flake-config github:juspay/omnix ci run github:juspay/hyperswitch`
### Context For The Bug
_No response_
### Environment
Both on NixOS and macOS
### 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/Cargo.nix b/Cargo.nix
deleted file mode 100644
index 1c3c3a086f5..00000000000
--- a/Cargo.nix
+++ /dev/null
@@ -1,5948 +0,0 @@
-# This file was @generated by cargo2nix 0.11.0.
-# It is not intended to be manually edited.
-
-args@{
- release ? true,
- rootFeatures ? [
- "api_models/default"
- "common_utils/default"
- "masking/default"
- "router_env/default"
- "router_derive/default"
- "drainer/default"
- "redis_interface/default"
- "diesel_models/default"
- "router/default"
- ],
- rustPackages,
- buildRustPackages,
- hostPlatform,
- hostPlatformCpu ? null,
- hostPlatformFeatures ? [],
- target ? null,
- codegenOpts ? null,
- profileOpts ? null,
- rustcLinkFlags ? null,
- rustcBuildFlags ? null,
- mkRustCrate,
- rustLib,
- lib,
- workspaceSrc,
-}:
-let
- workspaceSrc = if args.workspaceSrc == null then ./. else args.workspaceSrc;
-in let
- inherit (rustLib) fetchCratesIo fetchCrateLocal fetchCrateGit fetchCrateAlternativeRegistry expandFeatures decideProfile genDrvsByProfile;
- profilesByName = {
- release = builtins.fromTOML "codegen-units = 1\nlto = true\nstrip = true\n";
- };
- rootFeatures' = expandFeatures rootFeatures;
- overridableMkRustCrate = f:
- let
- drvs = genDrvsByProfile profilesByName ({ profile, profileName }: mkRustCrate ({ inherit release profile hostPlatformCpu hostPlatformFeatures target profileOpts codegenOpts rustcLinkFlags rustcBuildFlags; } // (f profileName)));
- in { compileMode ? null, profileName ? decideProfile compileMode release }:
- let drv = drvs.${profileName}; in if compileMode == null then drv else drv.override { inherit compileMode; };
-in
-{
- cargo2nixVersion = "0.11.0";
- workspace = {
- api_models = rustPackages.unknown.api_models."0.1.0";
- common_utils = rustPackages.unknown.common_utils."0.1.0";
- masking = rustPackages.unknown.masking."0.1.0";
- router_env = rustPackages.unknown.router_env."0.1.0";
- router_derive = rustPackages.unknown.router_derive."0.1.0";
- drainer = rustPackages.unknown.drainer."0.1.0";
- redis_interface = rustPackages.unknown.redis_interface."0.1.0";
- diesel_models = rustPackages.unknown.diesel_models."0.1.0";
- router = rustPackages.unknown.router."0.2.0";
- };
- "registry+https://github.com/rust-lang/crates.io-index".actix."0.13.0" = overridableMkRustCrate (profileName: rec {
- name = "actix";
- version = "0.13.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f728064aca1c318585bf4bb04ffcfac9e75e508ab4e8b1bd9ba5dfe04e2cbed5"; };
- features = builtins.concatLists [
- [ "actix_derive" ]
- [ "default" ]
- [ "macros" ]
- ];
- dependencies = {
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix_derive."0.6.0" { profileName = "__noProfile"; };
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" = overridableMkRustCrate (profileName: rec {
- name = "actix-codec";
- version = "0.5.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "57a7559404a7f3573127aab53c08ce37a6c6a315c374a31070f3c91cd1b4a7fe"; };
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-cors."0.6.4" = overridableMkRustCrate (profileName: rec {
- name = "actix-cors";
- version = "0.6.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b340e9cfa5b08690aae90fb61beb44e9b06f44fe3d0f93781aaa58cfba86245e"; };
- dependencies = {
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; };
- derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" = overridableMkRustCrate (profileName: rec {
- name = "actix-http";
- version = "3.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0070905b2c4a98d184c4e81025253cb192aa8a73827553f38e9410801ceb35bb"; };
- features = builtins.concatLists [
- [ "__compress" ]
- [ "base64" ]
- [ "brotli" ]
- [ "compress-brotli" ]
- [ "compress-gzip" ]
- [ "compress-zstd" ]
- [ "default" ]
- [ "flate2" ]
- [ "h2" ]
- [ "http2" ]
- [ "local-channel" ]
- [ "rand" ]
- [ "sha1" ]
- [ "ws" ]
- [ "zstd" ]
- ];
- dependencies = {
- actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; };
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; };
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; };
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- brotli = rustPackages."registry+https://github.com/rust-lang/crates.io-index".brotli."3.3.4" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; };
- derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; };
- encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; };
- flate2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- httparse = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" { inherit profileName; };
- httpdate = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- language_tags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" { inherit profileName; };
- local_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-channel."0.1.3" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- sha1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha1."0.10.5" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- zstd = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" = overridableMkRustCrate (profileName: rec {
- name = "actix-macros";
- version = "0.2.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6"; };
- dependencies = {
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" = overridableMkRustCrate (profileName: rec {
- name = "actix-router";
- version = "0.5.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "http" ]
- ];
- dependencies = {
- bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" = overridableMkRustCrate (profileName: rec {
- name = "actix-rt";
- version = "2.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "15265b6b8e2347670eb363c47fc8c75208b4a4994b27192f345fcbe707804f3e"; };
- features = builtins.concatLists [
- [ "actix-macros" ]
- [ "default" ]
- [ "macros" ]
- ];
- dependencies = {
- actix_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" { profileName = "__noProfile"; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-server."2.1.1" = overridableMkRustCrate (profileName: rec {
- name = "actix-server";
- version = "2.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0da34f8e659ea1b077bb4637948b815cd3768ad5a188fdcd74ff4d84240cd824"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; };
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- mio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" { inherit profileName; };
- num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; };
- socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" = overridableMkRustCrate (profileName: rec {
- name = "actix-service";
- version = "2.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a"; };
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- paste = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".paste."1.0.11" { profileName = "__noProfile"; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-tls."3.0.3" = overridableMkRustCrate (profileName: rec {
- name = "actix-tls";
- version = "3.0.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9fde0cf292f7cdc7f070803cb9a0d45c018441321a78b1042ffbbb81ec333297"; };
- features = builtins.concatLists [
- [ "accept" ]
- [ "connect" ]
- [ "default" ]
- [ "http" ]
- [ "rustls" ]
- [ "tokio-rustls" ]
- [ "uri" ]
- [ "webpki-roots" ]
- ];
- dependencies = {
- actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; };
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; };
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio_rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- webpki_roots = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" = overridableMkRustCrate (profileName: rec {
- name = "actix-utils";
- version = "3.0.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8"; };
- dependencies = {
- local_waker = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" = overridableMkRustCrate (profileName: rec {
- name = "actix-web";
- version = "4.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "464e0fddc668ede5f26ec1f9557a8d44eda948732f40c6b0ad79126930eb775f"; };
- features = builtins.concatLists [
- [ "__compress" ]
- [ "actix-macros" ]
- [ "actix-web-codegen" ]
- [ "compress-brotli" ]
- [ "compress-gzip" ]
- [ "compress-zstd" ]
- [ "cookie" ]
- [ "cookies" ]
- [ "default" ]
- [ "macros" ]
- ];
- dependencies = {
- actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; };
- actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; };
- actix_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" { profileName = "__noProfile"; };
- actix_router = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" { inherit profileName; };
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_server = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-server."2.1.1" { inherit profileName; };
- actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; };
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- actix_web_codegen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web-codegen."4.1.0" { profileName = "__noProfile"; };
- ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- cookie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" { inherit profileName; };
- derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; };
- encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- language_tags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix-web-codegen."4.1.0" = overridableMkRustCrate (profileName: rec {
- name = "actix-web-codegen";
- version = "4.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1fa9362663c8643d67b2d5eafba49e4cb2c8a053a29ed00a0bea121f17c76b13"; };
- dependencies = {
- actix_router = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".actix_derive."0.6.0" = overridableMkRustCrate (profileName: rec {
- name = "actix_derive";
- version = "0.6.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6d44b8fee1ced9671ba043476deddef739dd0959bf77030b26b738cc591737a7"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" = overridableMkRustCrate (profileName: rec {
- name = "adler";
- version = "1.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" = overridableMkRustCrate (profileName: rec {
- name = "ahash";
- version = "0.7.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- ${ if hostPlatform.parsed.kernel.name == "linux" || hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" || hostPlatform.parsed.kernel.name == "freebsd" || hostPlatform.parsed.kernel.name == "openbsd" || hostPlatform.parsed.kernel.name == "netbsd" || hostPlatform.parsed.kernel.name == "dragonfly" || hostPlatform.parsed.kernel.name == "solaris" || hostPlatform.parsed.kernel.name == "illumos" || hostPlatform.parsed.kernel.name == "fuchsia" || hostPlatform.parsed.kernel.name == "redox" || hostPlatform.parsed.kernel.name == "cloudabi" || hostPlatform.parsed.kernel.name == "haiku" || hostPlatform.parsed.kernel.name == "vxworks" || hostPlatform.parsed.kernel.name == "emscripten" || hostPlatform.parsed.kernel.name == "wasi" then "getrandom" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; };
- ${ if !((hostPlatform.parsed.cpu.name == "armv6l" || hostPlatform.parsed.cpu.name == "armv7l") && hostPlatform.parsed.kernel.name == "none") then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- };
- buildDependencies = {
- version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.20" = overridableMkRustCrate (profileName: rec {
- name = "aho-corasick";
- version = "0.7.20";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" = overridableMkRustCrate (profileName: rec {
- name = "alloc-no-stdlib";
- version = "2.0.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" = overridableMkRustCrate (profileName: rec {
- name = "alloc-stdlib";
- version = "0.2.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"; };
- dependencies = {
- alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" = overridableMkRustCrate (profileName: rec {
- name = "anyhow";
- version = "1.0.68";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "unknown".api_models."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "api_models";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/api_models");
- dependencies = {
- actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; };
- common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; };
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- reqwest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" { inherit profileName; };
- router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- utoipa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".arc-swap."1.6.0" = overridableMkRustCrate (profileName: rec {
- name = "arc-swap";
- version = "1.6.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".arcstr."1.1.5" = overridableMkRustCrate (profileName: rec {
- name = "arcstr";
- version = "1.1.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3f907281554a3d0312bb7aab855a8e0ef6cbf1614d06de54105039ca8b34460e"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "substr" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".arrayref."0.3.6" = overridableMkRustCrate (profileName: rec {
- name = "arrayref";
- version = "0.3.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".arrayvec."0.7.2" = overridableMkRustCrate (profileName: rec {
- name = "arrayvec";
- version = "0.7.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".assert-json-diff."2.0.2" = overridableMkRustCrate (profileName: rec {
- name = "assert-json-diff";
- version = "2.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"; };
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- };
- });
- "git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "async-bb8-diesel";
- version = "0.1.0";
- registry = "git+https://github.com/juspay/async-bb8-diesel";
- src = fetchCrateGit {
- url = https://github.com/juspay/async-bb8-diesel;
- name = "async-bb8-diesel";
- version = "0.1.0";
- rev = "9a71d142726dbc33f41c1fd935ddaa79841c7be5";};
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; };
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".async-channel."1.8.0" = overridableMkRustCrate (profileName: rec {
- name = "async-channel";
- version = "1.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cf46fee83e5ccffc220104713af3292ff9bc7c64c7de289f66dae8e38d826833"; };
- dependencies = {
- concurrent_queue = rustPackages."registry+https://github.com/rust-lang/crates.io-index".concurrent-queue."2.1.0" { inherit profileName; };
- event_listener = rustPackages."registry+https://github.com/rust-lang/crates.io-index".event-listener."2.5.3" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".async-compression."0.3.15" = overridableMkRustCrate (profileName: rec {
- name = "async-compression";
- version = "0.3.15";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "942c7cd7ae39e91bde4820d74132e9862e62c2f386c3aa90ccf55949f5bad63a"; };
- features = builtins.concatLists [
- [ "flate2" ]
- [ "gzip" ]
- [ "tokio" ]
- ];
- dependencies = {
- flate2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".async-stream."0.3.3" = overridableMkRustCrate (profileName: rec {
- name = "async-stream";
- version = "0.3.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dad5c83079eae9969be7fadefe640a1c566901f05ff91ab221de4b6f68d9507e"; };
- dependencies = {
- async_stream_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-stream-impl."0.3.3" { profileName = "__noProfile"; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".async-stream-impl."0.3.3" = overridableMkRustCrate (profileName: rec {
- name = "async-stream-impl";
- version = "0.3.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" = overridableMkRustCrate (profileName: rec {
- name = "async-trait";
- version = "0.1.63";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "eff18d764974428cf3a9328e23fc5c986f5fbed46e6cd4cdf42544df5d297ec1"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" = overridableMkRustCrate (profileName: rec {
- name = "atty";
- version = "0.2.14";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"; };
- dependencies = {
- ${ if hostPlatform.parsed.kernel.name == "hermit" then "hermit_abi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.1.19" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "autocfg";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".awc."3.1.0" = overridableMkRustCrate (profileName: rec {
- name = "awc";
- version = "3.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0dff3fc64a176e0d4398c71b0f2c2679ff4a723c6ed8fcc68dfe5baa00665388"; };
- features = builtins.concatLists [
- [ "__compress" ]
- [ "compress-brotli" ]
- [ "compress-gzip" ]
- [ "compress-zstd" ]
- [ "cookie" ]
- [ "cookies" ]
- [ "default" ]
- [ "rustls" ]
- [ "tls-rustls" ]
- ];
- dependencies = {
- actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; };
- actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; };
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; };
- actix_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-tls."3.0.3" { inherit profileName; };
- actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; };
- ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- cookie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" { inherit profileName; };
- derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- tls_rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-config."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-config";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3c3d1e2a1f1ab3ac6c4b884e37413eaa03eb9d901e4fc68ee8f5c1d49721680e"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "client-hyper")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_sso" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sso."0.24.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_sts" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sts."0.24.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "ring" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-credential-types";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bb0696a0523a39a19087747e4dafda0362dc867531e3d72a3f195564c84e5e08"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-endpoint";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "80a4f935ab6a1919fbfd6102a80c4fccd9ff5f47f94ba154074afe1051903261"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-http";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "82976ca4e426ee9ca3ffcf919d9b2c8d14d0cd80d43cc02173737a8f07f28d4d"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-kms."0.24.0" = overridableMkRustCrate (profileName: rec {
- name = "aws-sdk-kms";
- version = "0.24.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "434d7097fc824eee1d94cf6c5e3a30714da15b81a5b99618f8feb67f8eb2f70a"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio")
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sso."0.24.0" = overridableMkRustCrate (profileName: rec {
- name = "aws-sdk-sso";
- version = "0.24.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ca0119bacf0c42f587506769390983223ba834e605f049babe514b2bd646dbb2"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sts."0.24.0" = overridableMkRustCrate (profileName: rec {
- name = "aws-sdk-sts";
- version = "0.24.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "270b6a33969ebfcb193512fbd5e8ee5306888ad6c6d5d775cdbfb2d50d94de26"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_query" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-query."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_xml" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-xml."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-sig-auth";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "660a02a98ab1af83bd8d714afbab2d502ba9b18c49e7e4cddd6bf8837ff778cb"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sigv4" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sigv4."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-sigv4."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-sigv4";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cdaf11005b7444e6cd66f600d09861a3aeb6eb89a0f003c7c9820dbab2d15297"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "form_urlencoded")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "percent-encoding")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "sign-http")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "form_urlencoded" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hmac" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hmac."0.12.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "sha2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-async";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "075d87b46420b28b64140f2ba88fa6b158c2877466a2acdbeaf396c25e4b9b33"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "futures_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-client";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "17d44078855a64d757e5c1727df29ffa6679022c38cfc4ba4e63ee9567133141"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "client-hyper")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "hyper")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "hyper-rustls")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "lazy_static")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "fastrand" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper_rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-rustls."0.23.2" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-http";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b5bd86f48d7e36fb24ee922d04d79c8353e01724b1c38757ed92593179223aa7"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio")
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio")
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio-util")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes_utils" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "futures_core" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_utils" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-http-tower";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c8972d1b4ae3aba1a10e7106fed53a5a36bc8ef86170a84f6ddd33d36fac12ad"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-json";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "18973f12721e27b54891386497a57e1ba09975df1c6cfeccafaf541198962aef"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-query."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-query";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2881effde104a2b0619badaad9f30ae67805e86fbbdb99e5fcc176e8bfbc1a85"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "urlencoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-types";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "da7e499c4b15bab8eb6b234df31833cc83a1bdaa691ba72d5d81efc109d9d705"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "base64_simd" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64-simd."0.7.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "itoa" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "num_integer" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "ryu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-xml."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-smithy-xml";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9a73082f023f4a361fe811954da0061076709198792a3d2ad3a7498e10b606a0"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "xmlparser" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" = overridableMkRustCrate (profileName: rec {
- name = "aws-types";
- version = "0.54.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f8f15b34253b68cde08e39b0627cc6101bcca64351229484b4743392c035d057"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- buildDependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustc_version" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".axum."0.6.2" = overridableMkRustCrate (profileName: rec {
- name = "axum";
- version = "0.6.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1304eab461cf02bd70b083ed8273388f9724c549b316ba3d1e213ce0e9e7fb7e"; };
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- axum_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".axum-core."0.3.1" { inherit profileName; };
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- matchit = rustPackages."registry+https://github.com/rust-lang/crates.io-index".matchit."0.7.0" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- sync_wrapper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sync_wrapper."0.1.1" { inherit profileName; };
- tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- tower_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-http."0.3.5" { inherit profileName; };
- tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- };
- buildDependencies = {
- rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".axum-core."0.3.1" = overridableMkRustCrate (profileName: rec {
- name = "axum-core";
- version = "0.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f487e40dc9daee24d8a1779df88522f159a54a980f99cfbe43db0be0bd3444a8"; };
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- };
- buildDependencies = {
- rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" = overridableMkRustCrate (profileName: rec {
- name = "base64";
- version = "0.13.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" = overridableMkRustCrate (profileName: rec {
- name = "base64";
- version = "0.21.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".base64-simd."0.7.0" = overridableMkRustCrate (profileName: rec {
- name = "base64-simd";
- version = "0.7.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "781dd20c3aff0bd194fe7d2a977dd92f21c173891f3a03b677359e5fa457e5d5"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "alloc")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "detect")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "simd_abstraction" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" = overridableMkRustCrate (profileName: rec {
- name = "bb8";
- version = "0.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1627eccf3aa91405435ba240be23513eeca466b5dc33866422672264de061582"; };
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".bit-set."0.5.3" = overridableMkRustCrate (profileName: rec {
- name = "bit-set";
- version = "0.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- bit_vec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" = overridableMkRustCrate (profileName: rec {
- name = "bit-vec";
- version = "0.6.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" = overridableMkRustCrate (profileName: rec {
- name = "bitflags";
- version = "1.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".blake3."1.3.3" = overridableMkRustCrate (profileName: rec {
- name = "blake3";
- version = "1.3.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "digest" ]
- [ "std" ]
- ];
- dependencies = {
- arrayref = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arrayref."0.3.6" { inherit profileName; };
- arrayvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arrayvec."0.7.2" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- constant_time_eq = rustPackages."registry+https://github.com/rust-lang/crates.io-index".constant_time_eq."0.2.4" { inherit profileName; };
- digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; };
- };
- buildDependencies = {
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.9.0" = overridableMkRustCrate (profileName: rec {
- name = "block-buffer";
- version = "0.9.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"; };
- dependencies = {
- generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.10.3" = overridableMkRustCrate (profileName: rec {
- name = "block-buffer";
- version = "0.10.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"; };
- dependencies = {
- generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".brotli."3.3.4" = overridableMkRustCrate (profileName: rec {
- name = "brotli";
- version = "3.3.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68"; };
- features = builtins.concatLists [
- [ "alloc-stdlib" ]
- [ "default" ]
- [ "ffi-api" ]
- [ "std" ]
- ];
- dependencies = {
- alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; };
- alloc_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" { inherit profileName; };
- brotli_decompressor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" = overridableMkRustCrate (profileName: rec {
- name = "brotli-decompressor";
- version = "2.3.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744"; };
- features = builtins.concatLists [
- [ "alloc-stdlib" ]
- [ "std" ]
- ];
- dependencies = {
- alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; };
- alloc_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".bumpalo."3.12.0" = overridableMkRustCrate (profileName: rec {
- name = "bumpalo";
- version = "3.12.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" = overridableMkRustCrate (profileName: rec {
- name = "byteorder";
- version = "1.4.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" = overridableMkRustCrate (profileName: rec {
- name = "bytes";
- version = "1.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "bytes-utils";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e47d3a8076e283f3acd27400535992edb3ba4b5bb72f8891ad8fbe7932a7d4b9"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" = overridableMkRustCrate (profileName: rec {
- name = "bytestring";
- version = "1.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f7f83e57d9154148e355404702e2694463241880b939570d7c97c014da7a69a1"; };
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" = overridableMkRustCrate (profileName: rec {
- name = "cc";
- version = "1.0.78";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"; };
- features = builtins.concatLists [
- [ "jobserver" ]
- [ "parallel" ]
- ];
- dependencies = {
- jobserver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" = overridableMkRustCrate (profileName: rec {
- name = "cfg-if";
- version = "1.0.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" = overridableMkRustCrate (profileName: rec {
- name = "clap";
- version = "4.1.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f13b9c79b5d1dd500d20ef541215a6423c75829ef43117e1b4d17fd8af0b5d76"; };
- features = builtins.concatLists [
- [ "derive" ]
- [ "help" ]
- [ "std" ]
- [ "usage" ]
- ];
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- clap_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".clap_derive."4.1.0" { profileName = "__noProfile"; };
- clap_lex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap_lex."0.3.1" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".clap_derive."4.1.0" = overridableMkRustCrate (profileName: rec {
- name = "clap_derive";
- version = "4.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "684a277d672e91966334af371f1a7b5833f9aa00b07c84e92fbce95e00208ce8"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- heck = rustPackages."registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" { inherit profileName; };
- proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".clap_lex."0.3.1" = overridableMkRustCrate (profileName: rec {
- name = "clap_lex";
- version = "0.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade"; };
- dependencies = {
- os_str_bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" { inherit profileName; };
- };
- });
- "unknown".common_utils."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "common_utils";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/common_utils");
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
- masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; };
- nanoid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; };
- signal_hook_tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- devDependencies = {
- fake = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fake."2.5.0" { inherit profileName; };
- proptest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".concurrent-queue."2.1.0" = overridableMkRustCrate (profileName: rec {
- name = "concurrent-queue";
- version = "2.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c278839b831783b70278b14df4d45e1beb1aad306c07bb796637de9a0e323e8e"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" = overridableMkRustCrate (profileName: rec {
- name = "config";
- version = "0.13.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d379af7f68bfc21714c6c7dea883544201741d2ce8274bb12fa54f89507f52a7"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "ini" ]
- [ "json" ]
- [ "json5" ]
- [ "json5_rs" ]
- [ "ron" ]
- [ "rust-ini" ]
- [ "serde_json" ]
- [ "toml" ]
- [ "yaml" ]
- [ "yaml-rust" ]
- ];
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- json5_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".json5."0.4.1" { inherit profileName; };
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- nom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" { inherit profileName; };
- pathdiff = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pathdiff."0.2.1" { inherit profileName; };
- ron = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ron."0.7.1" { inherit profileName; };
- ini = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rust-ini."0.18.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- toml = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml."0.5.11" { inherit profileName; };
- yaml_rust = rustPackages."registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".constant_time_eq."0.2.4" = overridableMkRustCrate (profileName: rec {
- name = "constant_time_eq";
- version = "0.2.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f3ad85c1f65dc7b37604eb0e89748faf0b9653065f2a8ef69f96a687ec1e9279"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".convert_case."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "convert_case";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" = overridableMkRustCrate (profileName: rec {
- name = "cookie";
- version = "0.16.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb"; };
- features = builtins.concatLists [
- [ "percent-encode" ]
- [ "percent-encoding" ]
- ];
- dependencies = {
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- buildDependencies = {
- version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".cookie-factory."0.3.2" = overridableMkRustCrate (profileName: rec {
- name = "cookie-factory";
- version = "0.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".core-foundation."0.9.3" = overridableMkRustCrate (profileName: rec {
- name = "core-foundation";
- version = "0.9.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"; };
- dependencies = {
- core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" = overridableMkRustCrate (profileName: rec {
- name = "core-foundation-sys";
- version = "0.8.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" = overridableMkRustCrate (profileName: rec {
- name = "cpufeatures";
- version = "0.2.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"; };
- dependencies = {
- ${ if hostPlatform.config == "aarch64-apple-darwin" || hostPlatform.config == "aarch64-linux-android" || hostPlatform.parsed.cpu.name == "aarch64" && hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".crc16."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "crc16";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" = overridableMkRustCrate (profileName: rec {
- name = "crc32fast";
- version = "1.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" = overridableMkRustCrate (profileName: rec {
- name = "crossbeam-channel";
- version = "0.5.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521"; };
- features = builtins.concatLists [
- [ "crossbeam-utils" ]
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" = overridableMkRustCrate (profileName: rec {
- name = "crossbeam-utils";
- version = "0.8.14";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4fb766fa798726286dbbb842f174001dab8abc7b627a1dd86e0b7222a95d929f"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".crypto-common."0.1.6" = overridableMkRustCrate (profileName: rec {
- name = "crypto-common";
- version = "0.1.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; };
- typenum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" = overridableMkRustCrate (profileName: rec {
- name = "dashmap";
- version = "5.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; };
- lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".deadpool."0.9.5" = overridableMkRustCrate (profileName: rec {
- name = "deadpool";
- version = "0.9.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "421fe0f90f2ab22016f32a9881be5134fdd71c65298917084b0c7477cbc3856e"; };
- features = builtins.concatLists [
- [ "async-trait" ]
- [ "default" ]
- [ "managed" ]
- [ "unmanaged" ]
- ];
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- deadpool_runtime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".deadpool-runtime."0.1.2" { inherit profileName; };
- num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; };
- retain_mut = rustPackages."registry+https://github.com/rust-lang/crates.io-index".retain_mut."0.1.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".deadpool-runtime."0.1.2" = overridableMkRustCrate (profileName: rec {
- name = "deadpool-runtime";
- version = "0.1.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".derive_deref."1.1.1" = overridableMkRustCrate (profileName: rec {
- name = "derive_deref";
- version = "1.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dcdbcee2d9941369faba772587a565f4f534e42cb8d17e5295871de730163b2b"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" = overridableMkRustCrate (profileName: rec {
- name = "derive_more";
- version = "0.99.17";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"; };
- features = builtins.concatLists [
- [ "add" ]
- [ "add_assign" ]
- [ "as_mut" ]
- [ "as_ref" ]
- [ "constructor" ]
- [ "convert_case" ]
- [ "default" ]
- [ "deref" ]
- [ "deref_mut" ]
- [ "display" ]
- [ "error" ]
- [ "from" ]
- [ "from_str" ]
- [ "index" ]
- [ "index_mut" ]
- [ "into" ]
- [ "into_iterator" ]
- [ "is_variant" ]
- [ "iterator" ]
- [ "mul" ]
- [ "mul_assign" ]
- [ "not" ]
- [ "rustc_version" ]
- [ "sum" ]
- [ "try_into" ]
- [ "unwrap" ]
- ];
- dependencies = {
- convert_case = rustPackages."registry+https://github.com/rust-lang/crates.io-index".convert_case."0.4.0" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- buildDependencies = {
- rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" = overridableMkRustCrate (profileName: rec {
- name = "diesel";
- version = "2.0.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4391a22b19c916e50bec4d6140f29bdda3e3bb187223fe6e3ea0b6e4d1021c04"; };
- features = builtins.concatLists [
- [ "32-column-tables" ]
- [ "bitflags" ]
- [ "byteorder" ]
- [ "default" ]
- [ "itoa" ]
- [ "postgres" ]
- [ "postgres_backend" ]
- [ "pq-sys" ]
- [ "r2d2" ]
- [ "serde_json" ]
- [ "time" ]
- [ "with-deprecated" ]
- ];
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- byteorder = rustPackages."registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" { inherit profileName; };
- diesel_derives = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel_derives."2.0.1" { profileName = "__noProfile"; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- pq_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pq-sys."0.4.7" { inherit profileName; };
- r2d2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".r2d2."0.8.10" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".diesel_derives."2.0.1" = overridableMkRustCrate (profileName: rec {
- name = "diesel_derives";
- version = "2.0.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "143b758c91dbc3fe1fdcb0dba5bd13276c6a66422f2ef5795b58488248a310aa"; };
- features = builtins.concatLists [
- [ "32-column-tables" ]
- [ "default" ]
- [ "postgres" ]
- [ "with-deprecated" ]
- ];
- dependencies = {
- proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".digest."0.9.0" = overridableMkRustCrate (profileName: rec {
- name = "digest";
- version = "0.9.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "std" ]
- ];
- dependencies = {
- generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" = overridableMkRustCrate (profileName: rec {
- name = "digest";
- version = "0.10.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "block-buffer" ]
- [ "core-api" ]
- [ "default" ]
- [ "mac" ]
- [ "std" ]
- [ "subtle" ]
- ];
- dependencies = {
- block_buffer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.10.3" { inherit profileName; };
- crypto_common = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crypto-common."0.1.6" { inherit profileName; };
- subtle = rustPackages."registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".dlv-list."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "dlv-list";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257"; };
- });
- "unknown".drainer."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "drainer";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/drainer");
- dependencies = {
- async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; };
- bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; };
- clap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" { inherit profileName; };
- common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; };
- config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; };
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- redis_interface = rustPackages."unknown".redis_interface."0.1.0" { inherit profileName; };
- router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; };
- diesel_models = rustPackages."unknown".diesel_models."0.1.0" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- buildDependencies = {
- router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".dyn-clone."1.0.10" = overridableMkRustCrate (profileName: rec {
- name = "dyn-clone";
- version = "1.0.10";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c9b0705efd4599c15a38151f4721f7bc388306f61084d3bfd50bd07fbca5cb60"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" = overridableMkRustCrate (profileName: rec {
- name = "either";
- version = "1.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "use_std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" = overridableMkRustCrate (profileName: rec {
- name = "encoding_rs";
- version = "0.8.31";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".env_logger."0.7.1" = overridableMkRustCrate (profileName: rec {
- name = "env_logger";
- version = "0.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"; };
- features = builtins.concatLists [
- [ "atty" ]
- [ "default" ]
- [ "humantime" ]
- [ "regex" ]
- [ "termcolor" ]
- ];
- dependencies = {
- atty = rustPackages."registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" { inherit profileName; };
- humantime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".humantime."1.3.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- termcolor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" = overridableMkRustCrate (profileName: rec {
- name = "error-stack";
- version = "0.2.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "859d224e04b2d93d974c08e375dac9b8d1a513846e44c6666450a57b1ed963f9"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "pretty-print" ]
- [ "std" ]
- ];
- dependencies = {
- anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; };
- owo_colors = rustPackages."registry+https://github.com/rust-lang/crates.io-index".owo-colors."3.5.0" { inherit profileName; };
- };
- buildDependencies = {
- rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".event-listener."2.5.3" = overridableMkRustCrate (profileName: rec {
- name = "event-listener";
- version = "2.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".fake."2.5.0" = overridableMkRustCrate (profileName: rec {
- name = "fake";
- version = "2.5.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4d68f517805463f3a896a9d29c1d6ff09d3579ded64a7201b4069f8f9c0d52fd"; };
- dependencies = {
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" = overridableMkRustCrate (profileName: rec {
- name = "fastrand";
- version = "1.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499"; };
- dependencies = {
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "instant" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" = overridableMkRustCrate (profileName: rec {
- name = "flate2";
- version = "1.0.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "miniz_oxide" ]
- [ "rust_backend" ]
- ];
- dependencies = {
- crc32fast = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" { inherit profileName; };
- miniz_oxide = rustPackages."registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".float-cmp."0.8.0" = overridableMkRustCrate (profileName: rec {
- name = "float-cmp";
- version = "0.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e1267f4ac4f343772758f7b1bdcbe767c218bbab93bb432acbf5162bbf85a6c4"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "num-traits" ]
- [ "ratio" ]
- ];
- dependencies = {
- num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" = overridableMkRustCrate (profileName: rec {
- name = "fnv";
- version = "1.0.7";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".foreign-types."0.3.2" = overridableMkRustCrate (profileName: rec {
- name = "foreign-types";
- version = "0.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"; };
- dependencies = {
- foreign_types_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "foreign-types-shared";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "form_urlencoded";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"; };
- dependencies = {
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".fred."5.2.0" = overridableMkRustCrate (profileName: rec {
- name = "fred";
- version = "5.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6be0137d9045288f9c0a0659da3b74c196ad0263d2eafa0f5a73785a907bad14"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "enable-tls" ]
- [ "ignore-auth-error" ]
- [ "metrics" ]
- [ "native-tls" ]
- [ "partial-tracing" ]
- [ "pool-prefer-active" ]
- [ "tokio-native-tls" ]
- [ "tracing" ]
- [ "tracing-futures" ]
- ];
- dependencies = {
- arc_swap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arc-swap."1.6.0" { inherit profileName; };
- arcstr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arcstr."1.1.5" { inherit profileName; };
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- bytes_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- float_cmp = rustPackages."registry+https://github.com/rust-lang/crates.io-index".float-cmp."0.8.0" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.11.2" { inherit profileName; };
- pretty_env_logger = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pretty_env_logger."0.4.0" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- redis_protocol = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redis-protocol."4.1.0" { inherit profileName; };
- semver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" { inherit profileName; };
- sha1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha-1."0.9.8" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; };
- tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.6.10" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "frunk_proc_macros" ]
- [ "proc-macros" ]
- [ "std" ]
- [ "validated" ]
- ];
- dependencies = {
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- frunk_derives = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_derives."0.4.1" { profileName = "__noProfile"; };
- frunk_proc_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk_core";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk_derives."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk_derives";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173"; };
- dependencies = {
- frunk_proc_macro_helpers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk_proc_macro_helpers";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50"; };
- dependencies = {
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk_proc_macros";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0"; };
- dependencies = {
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- frunk_proc_macros_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros_impl."0.1.1" { profileName = "__noProfile"; };
- proc_macro_hack = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros_impl."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "frunk_proc_macros_impl";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653"; };
- dependencies = {
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- frunk_proc_macro_helpers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" { inherit profileName; };
- proc_macro_hack = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" { profileName = "__noProfile"; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "async-await" ]
- [ "default" ]
- [ "executor" ]
- [ "futures-executor" ]
- [ "std" ]
- ];
- dependencies = {
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_executor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" { inherit profileName; };
- futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-channel";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "futures-sink" ]
- [ "sink" ]
- [ "std" ]
- ];
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-core";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-executor";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-io";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-lite."1.12.0" = overridableMkRustCrate (profileName: rec {
- name = "futures-lite";
- version = "1.12.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "fastrand" ]
- [ "futures-io" ]
- [ "memchr" ]
- [ "parking" ]
- [ "std" ]
- [ "waker-fn" ]
- ];
- dependencies = {
- fastrand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- parking = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking."2.0.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- waker_fn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-macro."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-macro";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-sink";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-task";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-timer."3.0.2" = overridableMkRustCrate (profileName: rec {
- name = "futures-timer";
- version = "3.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" = overridableMkRustCrate (profileName: rec {
- name = "futures-util";
- version = "0.3.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "async-await" ]
- [ "async-await-macro" ]
- [ "channel" ]
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- [ "futures-channel" ]
- [ "futures-io" ]
- [ "futures-macro" ]
- [ "futures-sink" ]
- [ "io" ]
- [ "memchr" ]
- [ "sink" ]
- [ "slab" ]
- [ "std" ]
- ];
- dependencies = {
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; };
- futures_macro = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-macro."0.3.25" { profileName = "__noProfile"; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- pin_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" { inherit profileName; };
- slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" = overridableMkRustCrate (profileName: rec {
- name = "generic-array";
- version = "0.14.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"; };
- features = builtins.concatLists [
- [ "more_lengths" ]
- ];
- dependencies = {
- typenum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" { inherit profileName; };
- };
- buildDependencies = {
- version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".gethostname."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "gethostname";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8a329e22866dd78b35d2c639a4a23d7b950aeae300dfd79f4fb19f74055c2404"; };
- dependencies = {
- ${ if !hostPlatform.isWindows then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.isWindows then "windows" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" = overridableMkRustCrate (profileName: rec {
- name = "getrandom";
- version = "0.1.16";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" = overridableMkRustCrate (profileName: rec {
- name = "getrandom";
- version = "0.2.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".git2."0.16.1" = overridableMkRustCrate (profileName: rec {
- name = "git2";
- version = "0.16.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ccf7f68c2995f392c49fffb4f95ae2c873297830eb25c6bc4c114ce8f4562acc"; };
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- libgit2_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libgit2-sys."0.14.2+1.5.1" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" = overridableMkRustCrate (profileName: rec {
- name = "h2";
- version = "0.3.15";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4"; };
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" = overridableMkRustCrate (profileName: rec {
- name = "hashbrown";
- version = "0.12.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"; };
- features = builtins.concatLists [
- [ "ahash" ]
- [ "default" ]
- [ "inline-more" ]
- [ "raw" ]
- ];
- dependencies = {
- ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "heck";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.1.19" = overridableMkRustCrate (profileName: rec {
- name = "hermit-abi";
- version = "0.1.19";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.2.6" = overridableMkRustCrate (profileName: rec {
- name = "hermit-abi";
- version = "0.2.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" = overridableMkRustCrate (profileName: rec {
- name = "hex";
- version = "0.4.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".hmac."0.12.1" = overridableMkRustCrate (profileName: rec {
- name = "hmac";
- version = "0.12.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "digest" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" = overridableMkRustCrate (profileName: rec {
- name = "http";
- version = "0.2.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"; };
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" = overridableMkRustCrate (profileName: rec {
- name = "http-body";
- version = "0.4.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"; };
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".http-range-header."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "http-range-header";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".http-types."2.12.0" = overridableMkRustCrate (profileName: rec {
- name = "http-types";
- version = "2.12.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6e9b187a72d63adbfba487f48095306ac823049cb504ee195541e91c7775f5ad"; };
- features = builtins.concatLists [
- [ "http" ]
- [ "hyperium_http" ]
- ];
- dependencies = {
- anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; };
- async_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-channel."1.8.0" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- futures_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-lite."1.12.0" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- infer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".infer."0.2.3" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.7.3" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_qs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.8.5" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" = overridableMkRustCrate (profileName: rec {
- name = "httparse";
- version = "1.8.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" = overridableMkRustCrate (profileName: rec {
- name = "httpdate";
- version = "1.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".humantime."1.3.0" = overridableMkRustCrate (profileName: rec {
- name = "humantime";
- version = "1.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"; };
- dependencies = {
- quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" = overridableMkRustCrate (profileName: rec {
- name = "hyper";
- version = "0.14.23";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c"; };
- features = builtins.concatLists [
- [ "client" ]
- [ "default" ]
- [ "full" ]
- [ "h2" ]
- [ "http1" ]
- [ "http2" ]
- [ "runtime" ]
- [ "server" ]
- [ "socket2" ]
- [ "stream" ]
- [ "tcp" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- httparse = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" { inherit profileName; };
- httpdate = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- want = rustPackages."registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hyper-rustls."0.23.2" = overridableMkRustCrate (profileName: rec {
- name = "hyper-rustls";
- version = "0.23.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http1")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http2")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "log")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "logging")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "native-tokio")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls-native-certs")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tls12")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio-runtime")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls_native_certs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls-native-certs."0.6.2" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hyper-timeout."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "hyper-timeout";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1"; };
- dependencies = {
- hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_io_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".hyper-tls."0.5.0" = overridableMkRustCrate (profileName: rec {
- name = "hyper-tls";
- version = "0.5.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"; };
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".idna."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "idna";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"; };
- dependencies = {
- unicode_bidi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-bidi."0.3.8" { inherit profileName; };
- unicode_normalization = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" = overridableMkRustCrate (profileName: rec {
- name = "indexmap";
- version = "1.9.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"; };
- features = builtins.concatLists [
- [ "serde" ]
- [ "std" ]
- ];
- dependencies = {
- hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".infer."0.2.3" = overridableMkRustCrate (profileName: rec {
- name = "infer";
- version = "0.2.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" = overridableMkRustCrate (profileName: rec {
- name = "instant";
- version = "0.1.12";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ipnet."2.7.1" = overridableMkRustCrate (profileName: rec {
- name = "ipnet";
- version = "2.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" = overridableMkRustCrate (profileName: rec {
- name = "is_ci";
- version = "1.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".itertools."0.10.5" = overridableMkRustCrate (profileName: rec {
- name = "itertools";
- version = "0.10.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"; };
- features = builtins.concatLists [
- [ "use_alloc" ]
- ];
- dependencies = {
- either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".itoa."0.4.8" = overridableMkRustCrate (profileName: rec {
- name = "itoa";
- version = "0.4.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"; };
- features = builtins.concatLists [
- [ "i128" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" = overridableMkRustCrate (profileName: rec {
- name = "itoa";
- version = "1.0.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" = overridableMkRustCrate (profileName: rec {
- name = "jobserver";
- version = "0.1.25";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "068b1ee6743e4d11fb9c6a1e6064b3693a1b600e7f5f5988047d98b3dc9fb90b"; };
- dependencies = {
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".josekit."0.8.1" = overridableMkRustCrate (profileName: rec {
- name = "josekit";
- version = "0.8.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dee6af62ad98bdf699ad2ecc8323479a1fdc7aa5faa6043d93119d83f6c5fca8"; };
- dependencies = {
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "anyhow" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "base64" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "flate2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "openssl" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "serde" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "serde_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "thiserror" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" = overridableMkRustCrate (profileName: rec {
- name = "js-sys";
- version = "0.3.60";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47"; };
- dependencies = {
- wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".json5."0.4.1" = overridableMkRustCrate (profileName: rec {
- name = "json5";
- version = "0.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1"; };
- dependencies = {
- pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; };
- pest_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_derive."2.5.3" { profileName = "__noProfile"; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".jsonwebtoken."8.2.0" = overridableMkRustCrate (profileName: rec {
- name = "jsonwebtoken";
- version = "8.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "09f4f04699947111ec1733e71778d763555737579e44b85844cae8e1940a1828"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "pem" ]
- [ "simple_asn1" ]
- [ "use_pem" ]
- ];
- dependencies = {
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- pem = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pem."1.1.1" { inherit profileName; };
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- simple_asn1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" = overridableMkRustCrate (profileName: rec {
- name = "language-tags";
- version = "0.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" = overridableMkRustCrate (profileName: rec {
- name = "lazy_static";
- version = "1.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" = overridableMkRustCrate (profileName: rec {
- name = "libc";
- version = "0.2.139";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".libgit2-sys."0.14.2+1.5.1" = overridableMkRustCrate (profileName: rec {
- name = "libgit2-sys";
- version = "0.14.2+1.5.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7f3d95f6b51075fe9810a7ae22c7095f12b98005ab364d8544797a825ce946a4"; };
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- libz_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libz-sys."1.1.8" { inherit profileName; };
- };
- buildDependencies = {
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".libm."0.2.6" = overridableMkRustCrate (profileName: rec {
- name = "libm";
- version = "0.2.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" = overridableMkRustCrate (profileName: rec {
- name = "libmimalloc-sys";
- version = "0.1.30";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dd8c7cbf8b89019683667e347572e6d55a7df7ea36b0c4ce69961b0cde67b174"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/mimalloc") "secure")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/mimalloc" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- buildDependencies = {
- ${ if rootFeatures' ? "router/mimalloc" then "cc" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".libz-sys."1.1.8" = overridableMkRustCrate (profileName: rec {
- name = "libz-sys";
- version = "1.1.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf"; };
- features = builtins.concatLists [
- [ "libc" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- buildDependencies = {
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; };
- ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" = overridableMkRustCrate (profileName: rec {
- name = "linked-hash-map";
- version = "0.5.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".literally."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "literally";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f0d2be3f5a0d4d5c983d1f8ecc2a87676a0875a14feb9eebf0675f7c3e2f3c35"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".local-channel."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "local-channel";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c"; };
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- local_waker = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "local-waker";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" = overridableMkRustCrate (profileName: rec {
- name = "lock_api";
- version = "0.4.9";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"; };
- dependencies = {
- scopeguard = rustPackages."registry+https://github.com/rust-lang/crates.io-index".scopeguard."1.1.0" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" = overridableMkRustCrate (profileName: rec {
- name = "log";
- version = "0.4.17";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- };
- });
- "unknown".masking."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "masking";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/masking");
- features = builtins.concatLists [
- [ "alloc" ]
- (lib.optional (rootFeatures' ? "masking/bytes") "bytes")
- [ "default" ]
- [ "diesel" ]
- [ "serde" ]
- ];
- dependencies = {
- ${ if rootFeatures' ? "masking/bytes" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- subtle = rustPackages."registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" { inherit profileName; };
- zeroize = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; };
- };
- devDependencies = {
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".matchers."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "matchers";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"; };
- dependencies = {
- regex_automata = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".matchit."0.7.0" = overridableMkRustCrate (profileName: rec {
- name = "matchit";
- version = "0.7.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".maud."0.24.0" = overridableMkRustCrate (profileName: rec {
- name = "maud";
- version = "0.24.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "19aff2cd19eb4b93df29efa602652513b0f731f1d3474f6e377f763fddf61e58"; };
- features = builtins.concatLists [
- [ "actix-web" ]
- [ "actix-web-dep" ]
- [ "default" ]
- [ "futures-util" ]
- ];
- dependencies = {
- actix_web_dep = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."0.4.8" { inherit profileName; };
- maud_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" = overridableMkRustCrate (profileName: rec {
- name = "maud_macros";
- version = "0.24.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e5c114f6f24b08fdd4a25d2fb87a8b140df56b577723247b382e8b04c583f2eb"; };
- dependencies = {
- proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" = overridableMkRustCrate (profileName: rec {
- name = "memchr";
- version = "2.5.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".mimalloc."0.1.34" = overridableMkRustCrate (profileName: rec {
- name = "mimalloc";
- version = "0.1.34";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9dcb174b18635f7561a0c6c9fc2ce57218ac7523cf72c50af80e2d79ab8f3ba1"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/mimalloc") "default")
- (lib.optional (rootFeatures' ? "router/mimalloc") "secure")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/mimalloc" then "libmimalloc_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" = overridableMkRustCrate (profileName: rec {
- name = "mime";
- version = "0.3.16";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" = overridableMkRustCrate (profileName: rec {
- name = "minimal-lexical";
- version = "0.2.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" = overridableMkRustCrate (profileName: rec {
- name = "miniz_oxide";
- version = "0.6.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa"; };
- features = builtins.concatLists [
- [ "with-alloc" ]
- ];
- dependencies = {
- adler = rustPackages."registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" = overridableMkRustCrate (profileName: rec {
- name = "mio";
- version = "0.8.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "net" ]
- [ "os-ext" ]
- [ "os-poll" ]
- ];
- dependencies = {
- ${ if hostPlatform.isUnix || hostPlatform.parsed.kernel.name == "wasi" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" { inherit profileName; };
- ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "nanoid";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"; };
- dependencies = {
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" = overridableMkRustCrate (profileName: rec {
- name = "native-tls";
- version = "0.2.11";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e"; };
- dependencies = {
- ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" { inherit profileName; };
- ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl_probe" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" { inherit profileName; };
- ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "windows" then "schannel" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "security_framework" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "security_framework_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "tempfile" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" = overridableMkRustCrate (profileName: rec {
- name = "nom";
- version = "7.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- minimal_lexical = rustPackages."registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".nom8."0.2.0" = overridableMkRustCrate (profileName: rec {
- name = "nom8";
- version = "0.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ae01545c9c7fc4486ab7debaf2aad7003ac19431791868fb2e8066df97fad2f8"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".nu-ansi-term."0.46.0" = overridableMkRustCrate (profileName: rec {
- name = "nu-ansi-term";
- version = "0.46.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"; };
- dependencies = {
- overload = rustPackages."registry+https://github.com/rust-lang/crates.io-index".overload."0.1.1" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "windows" then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".num-bigint."0.4.3" = overridableMkRustCrate (profileName: rec {
- name = "num-bigint";
- version = "0.4.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f"; };
- dependencies = {
- num_integer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" { inherit profileName; };
- num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" = overridableMkRustCrate (profileName: rec {
- name = "num-integer";
- version = "0.1.45";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- [ "i128" ]
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std")
- ];
- dependencies = {
- num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" = overridableMkRustCrate (profileName: rec {
- name = "num-traits";
- version = "0.2.15";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"; };
- features = builtins.concatLists [
- [ "i128" ]
- [ "libm" ]
- [ "std" ]
- ];
- dependencies = {
- libm = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libm."0.2.6" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" = overridableMkRustCrate (profileName: rec {
- name = "num_cpus";
- version = "1.15.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"; };
- dependencies = {
- ${ if (hostPlatform.parsed.cpu.name == "x86_64" || hostPlatform.parsed.cpu.name == "aarch64") && hostPlatform.parsed.kernel.name == "hermit" then "hermit_abi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.2.6" { inherit profileName; };
- ${ if !hostPlatform.isWindows then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" = overridableMkRustCrate (profileName: rec {
- name = "once_cell";
- version = "1.17.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "race" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "opaque-debug";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" = overridableMkRustCrate (profileName: rec {
- name = "openssl";
- version = "0.10.45";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b102428fd03bc5edf97f62620f7298614c45cedf287c271e7ed450bbaf83f2e1"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- foreign_types = rustPackages."registry+https://github.com/rust-lang/crates.io-index".foreign-types."0.3.2" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- openssl_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-macros."0.1.0" { profileName = "__noProfile"; };
- ffi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".openssl-macros."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "openssl-macros";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" = overridableMkRustCrate (profileName: rec {
- name = "openssl-probe";
- version = "0.1.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" = overridableMkRustCrate (profileName: rec {
- name = "openssl-sys";
- version = "0.9.80";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "23bbbf7854cd45b83958ebe919f0e8e516793727652e27fda10a8384cfc790b7"; };
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; };
- ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; };
- };
- });
- "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec {
- name = "opentelemetry";
- version = "0.18.0";
- registry = "git+https://github.com/open-telemetry/opentelemetry-rust";
- src = fetchCrateGit {
- url = https://github.com/open-telemetry/opentelemetry-rust;
- name = "opentelemetry";
- version = "0.18.0";
- rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";};
- features = builtins.concatLists [
- [ "default" ]
- [ "metrics" ]
- [ "rt-tokio-current-thread" ]
- [ "trace" ]
- ];
- dependencies = {
- opentelemetry_api = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" { inherit profileName; };
- opentelemetry_sdk = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" { inherit profileName; };
- };
- });
- "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-otlp."0.11.0" = overridableMkRustCrate (profileName: rec {
- name = "opentelemetry-otlp";
- version = "0.11.0";
- registry = "git+https://github.com/open-telemetry/opentelemetry-rust";
- src = fetchCrateGit {
- url = https://github.com/open-telemetry/opentelemetry-rust;
- name = "opentelemetry-otlp";
- version = "0.11.0";
- rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";};
- features = builtins.concatLists [
- [ "default" ]
- [ "grpc-tonic" ]
- [ "http" ]
- [ "metrics" ]
- [ "prost" ]
- [ "tokio" ]
- [ "tonic" ]
- [ "trace" ]
- ];
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; };
- opentelemetry_proto = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-proto."0.1.0" { inherit profileName; };
- prost = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; };
- };
- });
- "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-proto."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "opentelemetry-proto";
- version = "0.1.0";
- registry = "git+https://github.com/open-telemetry/opentelemetry-rust";
- src = fetchCrateGit {
- url = https://github.com/open-telemetry/opentelemetry-rust;
- name = "opentelemetry-proto";
- version = "0.1.0";
- rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";};
- features = builtins.concatLists [
- [ "gen-tonic" ]
- [ "metrics" ]
- [ "prost" ]
- [ "tonic" ]
- [ "traces" ]
- ];
- dependencies = {
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; };
- prost = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; };
- tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; };
- };
- });
- "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" = overridableMkRustCrate (profileName: rec {
- name = "opentelemetry_api";
- version = "0.18.0";
- registry = "git+https://github.com/open-telemetry/opentelemetry-rust";
- src = fetchCrateGit {
- url = https://github.com/open-telemetry/opentelemetry-rust;
- name = "opentelemetry_api";
- version = "0.18.0";
- rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";};
- features = builtins.concatLists [
- [ "default" ]
- [ "fnv" ]
- [ "metrics" ]
- [ "pin-project-lite" ]
- [ "trace" ]
- ];
- dependencies = {
- fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; };
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "js_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- };
- });
- "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" = overridableMkRustCrate (profileName: rec {
- name = "opentelemetry_sdk";
- version = "0.18.0";
- registry = "git+https://github.com/open-telemetry/opentelemetry-rust";
- src = fetchCrateGit {
- url = https://github.com/open-telemetry/opentelemetry-rust;
- name = "opentelemetry_sdk";
- version = "0.18.0";
- rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";};
- features = builtins.concatLists [
- [ "async-trait" ]
- [ "crossbeam-channel" ]
- [ "dashmap" ]
- [ "default" ]
- [ "fnv" ]
- [ "metrics" ]
- [ "percent-encoding" ]
- [ "rand" ]
- [ "rt-tokio-current-thread" ]
- [ "tokio" ]
- [ "tokio-stream" ]
- [ "trace" ]
- ];
- dependencies = {
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; };
- dashmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" { inherit profileName; };
- fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; };
- futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; };
- futures_executor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- opentelemetry_api = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" = overridableMkRustCrate (profileName: rec {
- name = "ordered-multimap";
- version = "0.4.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a"; };
- dependencies = {
- dlv_list = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dlv-list."0.3.0" { inherit profileName; };
- hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" = overridableMkRustCrate (profileName: rec {
- name = "os_str_bytes";
- version = "6.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"; };
- features = builtins.concatLists [
- [ "raw_os_str" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "outref";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".overload."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "overload";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".owo-colors."3.5.0" = overridableMkRustCrate (profileName: rec {
- name = "owo-colors";
- version = "3.5.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"; };
- features = builtins.concatLists [
- [ "supports-color" ]
- [ "supports-colors" ]
- ];
- dependencies = {
- supports_color = rustPackages."registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".parking."2.0.0" = overridableMkRustCrate (profileName: rec {
- name = "parking";
- version = "2.0.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.11.2" = overridableMkRustCrate (profileName: rec {
- name = "parking_lot";
- version = "0.11.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- instant = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; };
- lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; };
- parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" = overridableMkRustCrate (profileName: rec {
- name = "parking_lot";
- version = "0.12.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; };
- parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" = overridableMkRustCrate (profileName: rec {
- name = "parking_lot_core";
- version = "0.8.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- instant = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" = overridableMkRustCrate (profileName: rec {
- name = "parking_lot_core";
- version = "0.9.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ba1ef8814b5c993410bb3adfad7a5ed269563e4a2f90c41f5d85be7fb47133bf"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".paste."1.0.11" = overridableMkRustCrate (profileName: rec {
- name = "paste";
- version = "1.0.11";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pathdiff."0.2.1" = overridableMkRustCrate (profileName: rec {
- name = "pathdiff";
- version = "0.2.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pem."1.1.1" = overridableMkRustCrate (profileName: rec {
- name = "pem";
- version = "1.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8"; };
- dependencies = {
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" = overridableMkRustCrate (profileName: rec {
- name = "percent-encoding";
- version = "2.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" = overridableMkRustCrate (profileName: rec {
- name = "pest";
- version = "2.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4257b4a04d91f7e9e6290be5d3da4804dd5784fafde3a497d73eb2b4a158c30a"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- [ "thiserror" ]
- ];
- dependencies = {
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- ucd_trie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pest_derive."2.5.3" = overridableMkRustCrate (profileName: rec {
- name = "pest_derive";
- version = "2.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "241cda393b0cdd65e62e07e12454f1f25d57017dcc514b1514cd3c4645e3a0a6"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; };
- pest_generator = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" = overridableMkRustCrate (profileName: rec {
- name = "pest_generator";
- version = "2.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "46b53634d8c8196302953c74d5352f33d0c512a9499bd2ce468fc9f4128fa27c"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; };
- pest_meta = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_meta."2.5.3" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pest_meta."2.5.3" = overridableMkRustCrate (profileName: rec {
- name = "pest_meta";
- version = "2.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0ef4f1332a8d4678b41966bb4cc1d0676880e84183a1ecc3f4b69f03e99c7a51"; };
- dependencies = {
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; };
- };
- buildDependencies = {
- sha2 = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" = overridableMkRustCrate (profileName: rec {
- name = "pin-project";
- version = "1.0.12";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc"; };
- dependencies = {
- pin_project_internal = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" = overridableMkRustCrate (profileName: rec {
- name = "pin-project-internal";
- version = "1.0.12";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" = overridableMkRustCrate (profileName: rec {
- name = "pin-project-lite";
- version = "0.2.9";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "pin-utils";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" = overridableMkRustCrate (profileName: rec {
- name = "pkg-config";
- version = "0.3.26";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" = overridableMkRustCrate (profileName: rec {
- name = "ppv-lite86";
- version = "0.2.17";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"; };
- features = builtins.concatLists [
- [ "simd" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".pq-sys."0.4.7" = overridableMkRustCrate (profileName: rec {
- name = "pq-sys";
- version = "0.4.7";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3b845d6d8ec554f972a2c5298aad68953fd64e7441e846075450b44656a016d1"; };
- buildDependencies = {
- ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".pretty_env_logger."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "pretty_env_logger";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d"; };
- dependencies = {
- env_logger = rustPackages."registry+https://github.com/rust-lang/crates.io-index".env_logger."0.7.1" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" = overridableMkRustCrate (profileName: rec {
- name = "proc-macro-error";
- version = "1.0.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "syn" ]
- [ "syn-error" ]
- ];
- dependencies = {
- proc_macro_error_attr = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error-attr."1.0.4" { profileName = "__noProfile"; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- buildDependencies = {
- version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error-attr."1.0.4" = overridableMkRustCrate (profileName: rec {
- name = "proc-macro-error-attr";
- version = "1.0.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- };
- buildDependencies = {
- version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" = overridableMkRustCrate (profileName: rec {
- name = "proc-macro-hack";
- version = "0.5.20+deprecated";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" = overridableMkRustCrate (profileName: rec {
- name = "proc-macro2";
- version = "1.0.50";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "proc-macro" ]
- ];
- dependencies = {
- unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "proptest";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "29f1b898011ce9595050a68e60f90bad083ff2987a695a42357134c8381fba70"; };
- features = builtins.concatLists [
- [ "bit-set" ]
- [ "break-dead-code" ]
- [ "default" ]
- [ "fork" ]
- [ "lazy_static" ]
- [ "quick-error" ]
- [ "regex-syntax" ]
- [ "rusty-fork" ]
- [ "std" ]
- [ "tempfile" ]
- [ "timeout" ]
- ];
- dependencies = {
- bit_set = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bit-set."0.5.3" { inherit profileName; };
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- byteorder = rustPackages."registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" { inherit profileName; };
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; };
- quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."2.0.1" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- rand_chacha = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" { inherit profileName; };
- rand_xorshift = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_xorshift."0.3.0" { inherit profileName; };
- regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; };
- rusty_fork = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rusty-fork."0.3.0" { inherit profileName; };
- tempfile = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; };
- unarray = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" = overridableMkRustCrate (profileName: rec {
- name = "prost";
- version = "0.11.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "21dc42e00223fc37204bd4aa177e69420c604ca4a183209a8f9de30c6d934698"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "prost-derive" ]
- [ "std" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- prost_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" = overridableMkRustCrate (profileName: rec {
- name = "prost-derive";
- version = "0.11.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8bda8c0881ea9f722eb9629376db3d0b903b462477c1aafcb0566610ac28ac5d"; };
- dependencies = {
- anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; };
- itertools = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itertools."0.10.5" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" = overridableMkRustCrate (profileName: rec {
- name = "quick-error";
- version = "1.2.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".quick-error."2.0.1" = overridableMkRustCrate (profileName: rec {
- name = "quick-error";
- version = "2.0.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" = overridableMkRustCrate (profileName: rec {
- name = "quote";
- version = "1.0.23";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "proc-macro" ]
- ];
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".r2d2."0.8.10" = overridableMkRustCrate (profileName: rec {
- name = "r2d2";
- version = "0.8.10";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93"; };
- dependencies = {
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- scheduled_thread_pool = rustPackages."registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand."0.7.3" = overridableMkRustCrate (profileName: rec {
- name = "rand";
- version = "0.7.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "getrandom" ]
- [ "getrandom_package" ]
- [ "libc" ]
- [ "std" ]
- ];
- dependencies = {
- getrandom_package = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if !(hostPlatform.parsed.kernel.name == "emscripten") then "rand_chacha" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.2.2" { inherit profileName; };
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "emscripten" then "rand_hc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" = overridableMkRustCrate (profileName: rec {
- name = "rand";
- version = "0.8.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "getrandom" ]
- [ "libc" ]
- [ "rand_chacha" ]
- [ "small_rng" ]
- [ "std" ]
- [ "std_rng" ]
- ];
- dependencies = {
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- rand_chacha = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" { inherit profileName; };
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.2.2" = overridableMkRustCrate (profileName: rec {
- name = "rand_chacha";
- version = "0.2.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- ppv_lite86 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" { inherit profileName; };
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" = overridableMkRustCrate (profileName: rec {
- name = "rand_chacha";
- version = "0.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- dependencies = {
- ppv_lite86 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" { inherit profileName; };
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" = overridableMkRustCrate (profileName: rec {
- name = "rand_core";
- version = "0.5.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "getrandom" ]
- [ "std" ]
- ];
- dependencies = {
- getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" = overridableMkRustCrate (profileName: rec {
- name = "rand_core";
- version = "0.6.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "getrandom" ]
- [ "std" ]
- ];
- dependencies = {
- getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" = overridableMkRustCrate (profileName: rec {
- name = "rand_hc";
- version = "0.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"; };
- dependencies = {
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rand_xorshift."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "rand_xorshift";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f"; };
- dependencies = {
- rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".redis-protocol."4.1.0" = overridableMkRustCrate (profileName: rec {
- name = "redis-protocol";
- version = "4.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9c31deddf734dc0a39d3112e73490e88b61a05e83e074d211f348404cee4d2c6"; };
- features = builtins.concatLists [
- [ "decode-mut" ]
- [ "default" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- bytes_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; };
- cookie_factory = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie-factory."0.3.2" { inherit profileName; };
- crc16 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc16."0.4.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- nom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" { inherit profileName; };
- };
- });
- "unknown".redis_interface."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "redis_interface";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/redis_interface");
- dependencies = {
- common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- fred = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fred."5.2.0" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- };
- devDependencies = {
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" = overridableMkRustCrate (profileName: rec {
- name = "redox_syscall";
- version = "0.2.16";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"; };
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" = overridableMkRustCrate (profileName: rec {
- name = "regex";
- version = "1.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733"; };
- features = builtins.concatLists [
- [ "aho-corasick" ]
- [ "default" ]
- [ "memchr" ]
- [ "perf" ]
- [ "perf-cache" ]
- [ "perf-dfa" ]
- [ "perf-inline" ]
- [ "perf-literal" ]
- [ "std" ]
- [ "unicode" ]
- [ "unicode-age" ]
- [ "unicode-bool" ]
- [ "unicode-case" ]
- [ "unicode-gencat" ]
- [ "unicode-perl" ]
- [ "unicode-script" ]
- [ "unicode-segment" ]
- ];
- dependencies = {
- aho_corasick = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.20" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" = overridableMkRustCrate (profileName: rec {
- name = "regex-automata";
- version = "0.1.10";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "regex-syntax" ]
- [ "std" ]
- ];
- dependencies = {
- regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" = overridableMkRustCrate (profileName: rec {
- name = "regex-syntax";
- version = "0.6.28";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "unicode" ]
- [ "unicode-age" ]
- [ "unicode-bool" ]
- [ "unicode-case" ]
- [ "unicode-gencat" ]
- [ "unicode-perl" ]
- [ "unicode-script" ]
- [ "unicode-segment" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".remove_dir_all."0.5.3" = overridableMkRustCrate (profileName: rec {
- name = "remove_dir_all";
- version = "0.5.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"; };
- dependencies = {
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" = overridableMkRustCrate (profileName: rec {
- name = "reqwest";
- version = "0.11.14";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "21eed90ec8570952d53b772ecf8f206aa1ec9a3d76b2521c56c42973f2d91ee9"; };
- features = builtins.concatLists [
- [ "__tls" ]
- [ "async-compression" ]
- [ "default" ]
- [ "default-tls" ]
- [ "gzip" ]
- [ "hyper-tls" ]
- [ "json" ]
- [ "native-tls" ]
- [ "native-tls-crate" ]
- [ "serde_json" ]
- [ "tokio-native-tls" ]
- [ "tokio-util" ]
- ];
- dependencies = {
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "async_compression" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-compression."0.3.15" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "encoding_rs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "h2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "hyper_tls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-tls."0.5.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "ipnet" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ipnet."2.7.1" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "js_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "mime" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "native_tls_crate" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio_native_tls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "wasm_bindgen" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "wasm_bindgen_futures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-futures."0.4.33" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; };
- ${ if hostPlatform.isWindows then "winreg" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".retain_mut."0.1.9" = overridableMkRustCrate (profileName: rec {
- name = "retain_mut";
- version = "0.1.9";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" = overridableMkRustCrate (profileName: rec {
- name = "ring";
- version = "0.16.20";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "dev_urandom_fallback" ]
- [ "once_cell" ]
- [ "std" ]
- ];
- dependencies = {
- ${ if hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "linux" || hostPlatform.parsed.kernel.name == "dragonfly" || hostPlatform.parsed.kernel.name == "freebsd" || hostPlatform.parsed.kernel.name == "illumos" || hostPlatform.parsed.kernel.name == "netbsd" || hostPlatform.parsed.kernel.name == "openbsd" || hostPlatform.parsed.kernel.name == "solaris" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" || (hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "armv6l" || hostPlatform.parsed.cpu.name == "armv7l") && (hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "fuchsia" || hostPlatform.parsed.kernel.name == "linux") then "spin" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".spin."0.5.2" { inherit profileName; };
- untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "wasm32" && hostPlatform.parsed.vendor.name == "unknown" && hostPlatform.parsed.kernel.name == "unknown" && hostPlatform.parsed.abi.name == "" then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "windows" then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- buildDependencies = {
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ron."0.7.1" = overridableMkRustCrate (profileName: rec {
- name = "ron";
- version = "0.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a"; };
- dependencies = {
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "unknown".router."0.2.0" = overridableMkRustCrate (profileName: rec {
- name = "router";
- version = "0.2.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/router");
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/accounts_cache" || rootFeatures' ? "router/default") "accounts_cache")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "aws-config")
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "aws-sdk-kms")
- (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/sandbox") "basilisk")
- (lib.optional (rootFeatures' ? "router/default") "default")
- (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "josekit")
- (lib.optional (rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "kms")
- (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/kv_store") "kv_store")
- (lib.optional (rootFeatures' ? "router/mimalloc") "mimalloc")
- (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/olap" || rootFeatures' ? "router/openapi") "olap")
- (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/oltp" || rootFeatures' ? "router/openapi") "oltp")
- (lib.optional (rootFeatures' ? "router/openapi") "openapi")
- (lib.optional (rootFeatures' ? "router/production") "production")
- (lib.optional (rootFeatures' ? "router/sandbox") "sandbox")
- (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe") "stripe")
- ];
- dependencies = {
- actix = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix."0.13.0" { inherit profileName; };
- actix_cors = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-cors."0.6.4" { inherit profileName; };
- actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; };
- actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; };
- api_models = rustPackages."unknown".api_models."0.1.0" { inherit profileName; };
- async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; };
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_config" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-config."0.54.1" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_kms" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-kms."0.24.0" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; };
- bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; };
- blake3 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".blake3."1.3.3" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- clap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" { inherit profileName; };
- common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; };
- config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; };
- crc32fast = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" { inherit profileName; };
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- dyn_clone = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dyn-clone."1.0.10" { inherit profileName; };
- encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; };
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "josekit" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".josekit."0.8.1" { inherit profileName; };
- jsonwebtoken = rustPackages."registry+https://github.com/rust-lang/crates.io-index".jsonwebtoken."8.2.0" { inherit profileName; };
- literally = rustPackages."registry+https://github.com/rust-lang/crates.io-index".literally."0.1.3" { inherit profileName; };
- masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; };
- maud = rustPackages."registry+https://github.com/rust-lang/crates.io-index".maud."0.24.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/mimalloc" then "mimalloc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mimalloc."0.1.34" { inherit profileName; };
- mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; };
- nanoid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" { inherit profileName; };
- num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- redis_interface = rustPackages."unknown".redis_interface."0.1.0" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- reqwest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" { inherit profileName; };
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; };
- router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; };
- ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "serde_qs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.11.0" { inherit profileName; };
- serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; };
- signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; };
- signal_hook_tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" { inherit profileName; };
- diesel_models = rustPackages."unknown".diesel_models."0.1.0" { inherit profileName; };
- strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; };
- utoipa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" { inherit profileName; };
- uuid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" { inherit profileName; };
- };
- devDependencies = {
- actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; };
- awc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".awc."3.1.0" { inherit profileName; };
- derive_deref = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_deref."1.1.1" { profileName = "__noProfile"; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- serial_test = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serial_test."1.0.0" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- toml = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml."0.7.2" { inherit profileName; };
- wiremock = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wiremock."0.5.17" { inherit profileName; };
- };
- buildDependencies = {
- router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; };
- };
- });
- "unknown".router_derive."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "router_derive";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/router_derive");
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- devDependencies = {
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; };
- };
- });
- "unknown".router_env."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "router_env";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/router_env");
- features = builtins.concatLists [
- [ "actix_web" ]
- [ "default" ]
- [ "log_custom_entries_to_extra" ]
- [ "log_extra_implicit_fields" ]
- [ "tracing-actix-web" ]
- [ "vergen" ]
- ];
- dependencies = {
- config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; };
- gethostname = rustPackages."registry+https://github.com/rust-lang/crates.io-index".gethostname."0.4.1" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; };
- opentelemetry_otlp = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-otlp."0.11.0" { inherit profileName; };
- rustc_hash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc-hash."1.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; };
- strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-actix-web."0.7.2" { inherit profileName; };
- tracing_appender = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-appender."0.2.2" { inherit profileName; };
- tracing_attributes = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" { profileName = "__noProfile"; };
- tracing_opentelemetry = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" { inherit profileName; };
- tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; };
- vergen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" { inherit profileName; };
- };
- devDependencies = {
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- buildDependencies = {
- vergen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rust-ini."0.18.0" = overridableMkRustCrate (profileName: rec {
- name = "rust-ini";
- version = "0.18.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ordered_multimap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustc-hash."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "rustc-hash";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "rustc_version";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"; };
- dependencies = {
- semver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" = overridableMkRustCrate (profileName: rec {
- name = "rustls";
- version = "0.20.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"; };
- features = builtins.concatLists [
- [ "dangerous_configuration" ]
- [ "default" ]
- [ "log" ]
- [ "logging" ]
- [ "tls12" ]
- ];
- dependencies = {
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- sct = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sct."0.7.0" { inherit profileName; };
- webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustls-native-certs."0.6.2" = overridableMkRustCrate (profileName: rec {
- name = "rustls-native-certs";
- version = "0.6.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0167bac7a9f490495f3c33013e7722b53cb087ecbe082fb0c6387c96f634ea50"; };
- dependencies = {
- ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.isUnix && !(hostPlatform.parsed.kernel.name == "darwin") then "openssl_probe" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" { inherit profileName; };
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls_pemfile" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls-pemfile."1.0.2" { inherit profileName; };
- ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.isWindows then "schannel" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" { inherit profileName; };
- ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.parsed.kernel.name == "darwin" then "security_framework" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustls-pemfile."1.0.2" = overridableMkRustCrate (profileName: rec {
- name = "rustls-pemfile";
- version = "1.0.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"; };
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "base64" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" = overridableMkRustCrate (profileName: rec {
- name = "rustversion";
- version = "1.0.11";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".rusty-fork."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "rusty-fork";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f"; };
- features = builtins.concatLists [
- [ "timeout" ]
- [ "wait-timeout" ]
- ];
- dependencies = {
- fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; };
- quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" { inherit profileName; };
- tempfile = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; };
- wait_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" = overridableMkRustCrate (profileName: rec {
- name = "ryu";
- version = "1.0.12";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" = overridableMkRustCrate (profileName: rec {
- name = "schannel";
- version = "0.1.21";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3"; };
- dependencies = {
- windows_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" = overridableMkRustCrate (profileName: rec {
- name = "scheduled-thread-pool";
- version = "0.2.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "977a7519bff143a44f842fd07e80ad1329295bd71686457f18e496736f4bf9bf"; };
- dependencies = {
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".scopeguard."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "scopeguard";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sct."0.7.0" = overridableMkRustCrate (profileName: rec {
- name = "sct";
- version = "0.7.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"; };
- dependencies = {
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" = overridableMkRustCrate (profileName: rec {
- name = "security-framework";
- version = "2.7.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c"; };
- features = builtins.concatLists [
- [ "OSX_10_9" ]
- [ "default" ]
- ];
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- core_foundation = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation."0.9.3" { inherit profileName; };
- core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- security_framework_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" = overridableMkRustCrate (profileName: rec {
- name = "security-framework-sys";
- version = "2.6.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556"; };
- features = builtins.concatLists [
- [ "OSX_10_9" ]
- [ "default" ]
- ];
- dependencies = {
- core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" = overridableMkRustCrate (profileName: rec {
- name = "semver";
- version = "1.0.16";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" = overridableMkRustCrate (profileName: rec {
- name = "serde";
- version = "1.0.152";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bb7d1f0d3021d347a83e556fc4683dea2ea09d87bccdf88ff5c12545d89d5efb"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "derive" ]
- [ "serde_derive" ]
- [ "std" ]
- ];
- dependencies = {
- serde_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" = overridableMkRustCrate (profileName: rec {
- name = "serde_derive";
- version = "1.0.152";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" = overridableMkRustCrate (profileName: rec {
- name = "serde_json";
- version = "1.0.91";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883"; };
- features = builtins.concatLists [
- [ "default" ]
- (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "indexmap")
- (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "preserve_order")
- [ "std" ]
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "indexmap" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- ryu = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" = overridableMkRustCrate (profileName: rec {
- name = "serde_path_to_error";
- version = "0.1.9";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "26b04f22b563c91331a10074bda3dd5492e3cc39d56bd557e91c0af42b6c7341"; };
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.8.5" = overridableMkRustCrate (profileName: rec {
- name = "serde_qs";
- version = "0.8.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c7715380eec75f029a4ef7de39a9200e0a63823176b759d055b613f5a87df6a6"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.11.0" = overridableMkRustCrate (profileName: rec {
- name = "serde_qs";
- version = "0.11.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c679fa27b429f2bb57fd4710257e643e86c966e716037259f8baa33de594a1b6"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe") "default")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "serde" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "thiserror" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" = overridableMkRustCrate (profileName: rec {
- name = "serde_spanned";
- version = "0.6.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4"; };
- features = builtins.concatLists [
- [ "serde" ]
- ];
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" = overridableMkRustCrate (profileName: rec {
- name = "serde_urlencoded";
- version = "0.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"; };
- dependencies = {
- form_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; };
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- ryu = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serial_test."1.0.0" = overridableMkRustCrate (profileName: rec {
- name = "serial_test";
- version = "1.0.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "538c30747ae860d6fb88330addbbd3e0ddbe46d662d032855596d8a8ca260611"; };
- features = builtins.concatLists [
- [ "async" ]
- [ "default" ]
- [ "futures" ]
- [ "log" ]
- [ "logging" ]
- ];
- dependencies = {
- dashmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- serial_test_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" = overridableMkRustCrate (profileName: rec {
- name = "serial_test_derive";
- version = "1.0.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "079a83df15f85d89a68d64ae1238f142f172b1fa915d0d76b26a7cba1b659a69"; };
- features = builtins.concatLists [
- [ "async" ]
- ];
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sha-1."0.9.8" = overridableMkRustCrate (profileName: rec {
- name = "sha-1";
- version = "0.9.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- block_buffer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.9.0" { inherit profileName; };
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; };
- digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.9.0" { inherit profileName; };
- opaque_debug = rustPackages."registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sha1."0.10.5" = overridableMkRustCrate (profileName: rec {
- name = "sha1";
- version = "0.10.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; };
- digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" = overridableMkRustCrate (profileName: rec {
- name = "sha2";
- version = "0.10.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std")
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "x86_64" || hostPlatform.parsed.cpu.name == "i686" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; };
- digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sharded-slab."0.1.4" = overridableMkRustCrate (profileName: rec {
- name = "sharded-slab";
- version = "0.1.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"; };
- dependencies = {
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" = overridableMkRustCrate (profileName: rec {
- name = "signal-hook";
- version = "0.3.14";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a253b5e89e2698464fc26b545c9edceb338e18a89effeeecfea192c3025be29d"; };
- features = builtins.concatLists [
- [ "channel" ]
- [ "default" ]
- [ "iterator" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- signal_hook_registry = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" = overridableMkRustCrate (profileName: rec {
- name = "signal-hook-registry";
- version = "1.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"; };
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" = overridableMkRustCrate (profileName: rec {
- name = "signal-hook-tokio";
- version = "0.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "213241f76fb1e37e27de3b6aa1b068a2c333233b59cca6634f634b80a27ecf1e"; };
- features = builtins.concatLists [
- [ "futures-core-0_3" ]
- [ "futures-v0_3" ]
- ];
- dependencies = {
- futures_core_0_3 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" = overridableMkRustCrate (profileName: rec {
- name = "simd-abstraction";
- version = "0.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9cadb29c57caadc51ff8346233b5cec1d240b68ce55cf1afc764818791876987"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "alloc")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "detect")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std")
- ];
- dependencies = {
- ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "outref" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" = overridableMkRustCrate (profileName: rec {
- name = "simple_asn1";
- version = "0.6.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "adc4e5204eb1910f40f9cfa375f6f05b68c3abac4b6fd879c8ff5e7ae8a0a085"; };
- dependencies = {
- num_bigint = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-bigint."0.4.3" { inherit profileName; };
- num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" = overridableMkRustCrate (profileName: rec {
- name = "slab";
- version = "0.4.7";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" = overridableMkRustCrate (profileName: rec {
- name = "smallvec";
- version = "1.10.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" = overridableMkRustCrate (profileName: rec {
- name = "socket2";
- version = "0.4.7";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"; };
- features = builtins.concatLists [
- [ "all" ]
- ];
- dependencies = {
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".spin."0.5.2" = overridableMkRustCrate (profileName: rec {
- name = "spin";
- version = "0.5.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"; };
- });
- "unknown".diesel_models."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "diesel_models";
- version = "0.1.0";
- registry = "unknown";
- src = fetchCrateLocal (workspaceSrc + "/crates/diesel_models");
- features = builtins.concatLists [
- [ "default" ]
- [ "kv_store" ]
- ];
- dependencies = {
- async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; };
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; };
- diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; };
- error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; };
- frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; };
- frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; };
- hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
- masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; };
- router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; };
- router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; };
- thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" = overridableMkRustCrate (profileName: rec {
- name = "strum";
- version = "0.24.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "derive" ]
- [ "std" ]
- [ "strum_macros" ]
- ];
- dependencies = {
- strum_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" = overridableMkRustCrate (profileName: rec {
- name = "strum_macros";
- version = "0.24.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59"; };
- dependencies = {
- heck = rustPackages."registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" = overridableMkRustCrate (profileName: rec {
- name = "subtle";
- version = "2.4.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "i128" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" = overridableMkRustCrate (profileName: rec {
- name = "supports-color";
- version = "1.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8ba6faf2ca7ee42fdd458f4347ae0a9bd6bcc445ad7cb57ad82b383f18870d6f"; };
- dependencies = {
- atty = rustPackages."registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" { inherit profileName; };
- is_ci = rustPackages."registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" = overridableMkRustCrate (profileName: rec {
- name = "syn";
- version = "1.0.107";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5"; };
- features = builtins.concatLists [
- [ "clone-impls" ]
- [ "default" ]
- [ "derive" ]
- [ "extra-traits" ]
- [ "fold" ]
- [ "full" ]
- [ "parsing" ]
- [ "printing" ]
- [ "proc-macro" ]
- [ "quote" ]
- [ "visit" ]
- [ "visit-mut" ]
- ];
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".sync_wrapper."0.1.1" = overridableMkRustCrate (profileName: rec {
- name = "sync_wrapper";
- version = "0.1.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "20518fe4a4c9acf048008599e464deb21beeae3d3578418951a189c235a7a9a8"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" = overridableMkRustCrate (profileName: rec {
- name = "tempfile";
- version = "3.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- fastrand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; };
- ${ if hostPlatform.isUnix || hostPlatform.parsed.kernel.name == "wasi" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; };
- remove_dir_all = rustPackages."registry+https://github.com/rust-lang/crates.io-index".remove_dir_all."0.5.3" { inherit profileName; };
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" = overridableMkRustCrate (profileName: rec {
- name = "termcolor";
- version = "1.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"; };
- dependencies = {
- ${ if hostPlatform.isWindows then "winapi_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" = overridableMkRustCrate (profileName: rec {
- name = "thiserror";
- version = "1.0.38";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"; };
- dependencies = {
- thiserror_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" = overridableMkRustCrate (profileName: rec {
- name = "thiserror-impl";
- version = "1.0.38";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".thread_local."1.1.4" = overridableMkRustCrate (profileName: rec {
- name = "thread_local";
- version = "1.1.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180"; };
- dependencies = {
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" = overridableMkRustCrate (profileName: rec {
- name = "time";
- version = "0.3.17";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "formatting" ]
- [ "macros" ]
- [ "parsing" ]
- [ "serde" ]
- [ "serde-well-known" ]
- [ "std" ]
- ];
- dependencies = {
- itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- time_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" { inherit profileName; };
- time_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "time-core";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" = overridableMkRustCrate (profileName: rec {
- name = "time-macros";
- version = "0.2.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"; };
- features = builtins.concatLists [
- [ "formatting" ]
- [ "parsing" ]
- [ "serde" ]
- ];
- dependencies = {
- time_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" = overridableMkRustCrate (profileName: rec {
- name = "tinyvec";
- version = "1.6.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "default" ]
- [ "tinyvec_macros" ]
- ];
- dependencies = {
- tinyvec_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "tinyvec_macros";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" = overridableMkRustCrate (profileName: rec {
- name = "tokio";
- version = "1.25.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af"; };
- features = builtins.concatLists [
- [ "bytes" ]
- [ "default" ]
- (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "fs")
- [ "io-std" ]
- [ "io-util" ]
- [ "libc" ]
- [ "macros" ]
- [ "memchr" ]
- [ "mio" ]
- [ "net" ]
- [ "num_cpus" ]
- [ "parking_lot" ]
- [ "rt" ]
- [ "rt-multi-thread" ]
- [ "signal" ]
- [ "signal-hook-registry" ]
- [ "socket2" ]
- [ "sync" ]
- [ "time" ]
- [ "tokio-macros" ]
- [ "windows-sys" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; };
- mio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" { inherit profileName; };
- num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; };
- parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- ${ if hostPlatform.isUnix then "signal_hook_registry" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" { inherit profileName; };
- ${ if !(hostPlatform.parsed.cpu.name == "wasm32" || hostPlatform.parsed.cpu.name == "wasm64") then "socket2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; };
- tokio_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-macros."1.8.2" { profileName = "__noProfile"; };
- ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; };
- };
- buildDependencies = {
- autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" = overridableMkRustCrate (profileName: rec {
- name = "tokio-io-timeout";
- version = "1.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "30b74022ada614a1b4834de765f9bb43877f910cc8ce4be40e89042c9223a8bf"; };
- dependencies = {
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-macros."1.8.2" = overridableMkRustCrate (profileName: rec {
- name = "tokio-macros";
- version = "1.8.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "tokio-native-tls";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b"; };
- dependencies = {
- native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" = overridableMkRustCrate (profileName: rec {
- name = "tokio-rustls";
- version = "0.23.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "logging" ]
- [ "tls12" ]
- ];
- dependencies = {
- rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" = overridableMkRustCrate (profileName: rec {
- name = "tokio-stream";
- version = "0.1.11";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "d660770404473ccd7bc9f8b28494a811bc18542b915c0855c51e8f419d5223ce"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "time" ]
- ];
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.6.10" = overridableMkRustCrate (profileName: rec {
- name = "tokio-util";
- version = "0.6.10";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507"; };
- features = builtins.concatLists [
- [ "codec" ]
- [ "default" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" = overridableMkRustCrate (profileName: rec {
- name = "tokio-util";
- version = "0.7.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740"; };
- features = builtins.concatLists [
- [ "codec" ]
- [ "default" ]
- [ "io" ]
- [ "tracing" ]
- ];
- dependencies = {
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".toml."0.5.11" = overridableMkRustCrate (profileName: rec {
- name = "toml";
- version = "0.5.11";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"; };
- features = builtins.concatLists [
- [ "default" ]
- ];
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".toml."0.7.2" = overridableMkRustCrate (profileName: rec {
- name = "toml";
- version = "0.7.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f7afcae9e3f0fe2c370fd4657108972cbb2fa9db1b9f84849cefd80741b01cb6"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "display" ]
- [ "parse" ]
- ];
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_spanned = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" { inherit profileName; };
- toml_datetime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" { inherit profileName; };
- toml_edit = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" = overridableMkRustCrate (profileName: rec {
- name = "toml_datetime";
- version = "0.6.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622"; };
- features = builtins.concatLists [
- [ "serde" ]
- ];
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" = overridableMkRustCrate (profileName: rec {
- name = "toml_edit";
- version = "0.19.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5e6a7712b49e1775fb9a7b998de6635b299237f48b404dde71704f2e0e7f37e5"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "serde" ]
- ];
- dependencies = {
- indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- nom8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom8."0.2.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_spanned = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" { inherit profileName; };
- toml_datetime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" = overridableMkRustCrate (profileName: rec {
- name = "tonic";
- version = "0.8.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8f219fad3b929bef19b1f86fbc0358d35daed8f2cac972037ac0dc10bbb8d5fb"; };
- features = builtins.concatLists [
- [ "async-trait" ]
- [ "axum" ]
- [ "channel" ]
- [ "codegen" ]
- [ "default" ]
- [ "h2" ]
- [ "hyper" ]
- [ "hyper-timeout" ]
- [ "prost" ]
- [ "prost-derive" ]
- [ "prost1" ]
- [ "tokio" ]
- [ "tower" ]
- [ "tracing-futures" ]
- [ "transport" ]
- ];
- dependencies = {
- async_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-stream."0.3.3" { inherit profileName; };
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- axum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".axum."0.6.2" { inherit profileName; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- hyper_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-timeout."0.4.1" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; };
- prost1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; };
- prost_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" { profileName = "__noProfile"; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" = overridableMkRustCrate (profileName: rec {
- name = "tower";
- version = "0.4.13";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"; };
- features = builtins.concatLists [
- [ "__common" ]
- [ "balance" ]
- [ "buffer" ]
- [ "default" ]
- [ "discover" ]
- [ "futures-core" ]
- [ "futures-util" ]
- [ "indexmap" ]
- [ "limit" ]
- [ "load" ]
- [ "log" ]
- [ "make" ]
- [ "pin-project" ]
- [ "pin-project-lite" ]
- [ "rand" ]
- [ "ready-cache" ]
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "retry")
- [ "slab" ]
- [ "timeout" ]
- [ "tokio" ]
- [ "tokio-util" ]
- [ "tracing" ]
- [ "util" ]
- ];
- dependencies = {
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; };
- slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; };
- tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tower-http."0.3.5" = overridableMkRustCrate (profileName: rec {
- name = "tower-http";
- version = "0.3.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f873044bf02dd1e8239e9c1293ea39dad76dc594ec16185d0a1bf31d8dc8d858"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "map-response-body" ]
- [ "tower" ]
- [ "util" ]
- ];
- dependencies = {
- bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; };
- bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; };
- futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; };
- futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; };
- http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; };
- http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; };
- http_range_header = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-range-header."0.3.0" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; };
- tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; };
- tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" = overridableMkRustCrate (profileName: rec {
- name = "tower-layer";
- version = "0.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" = overridableMkRustCrate (profileName: rec {
- name = "tower-service";
- version = "0.3.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" = overridableMkRustCrate (profileName: rec {
- name = "tracing";
- version = "0.1.36";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307"; };
- features = builtins.concatLists [
- [ "attributes" ]
- [ "default" ]
- [ "log" ]
- [ "std" ]
- [ "tracing-attributes" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; };
- tracing_attributes = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" { profileName = "__noProfile"; };
- tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-actix-web."0.7.2" = overridableMkRustCrate (profileName: rec {
- name = "tracing-actix-web";
- version = "0.7.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4082e4d81173e0b7ad3cfb71e9eaef0dd0cbb7b139fdb56394f488a3b0760b23"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "emit_event_on_error" ]
- [ "opentelemetry_0_18" ]
- [ "opentelemetry_0_18_pkg" ]
- [ "tracing-opentelemetry_0_18_pkg" ]
- ];
- dependencies = {
- actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; };
- opentelemetry_0_18_pkg = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; };
- pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_opentelemetry_0_18_pkg = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" { inherit profileName; };
- uuid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-appender."0.2.2" = overridableMkRustCrate (profileName: rec {
- name = "tracing-appender";
- version = "0.2.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e"; };
- dependencies = {
- crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" = overridableMkRustCrate (profileName: rec {
- name = "tracing-attributes";
- version = "0.1.22";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "11c75893af559bc8e10716548bdef5cb2b983f8e637db9d0e15126b61b484ee2"; };
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" = overridableMkRustCrate (profileName: rec {
- name = "tracing-core";
- version = "0.1.30";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "once_cell" ]
- [ "std" ]
- [ "valuable" ]
- ];
- dependencies = {
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- ${ if false then "valuable" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" = overridableMkRustCrate (profileName: rec {
- name = "tracing-futures";
- version = "0.2.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "pin-project" ]
- [ "std" ]
- [ "std-future" ]
- ];
- dependencies = {
- pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "tracing-log";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922"; };
- features = builtins.concatLists [
- [ "log-tracer" ]
- [ "std" ]
- ];
- dependencies = {
- lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec {
- name = "tracing-opentelemetry";
- version = "0.18.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "21ebb87a95ea13271332df069020513ab70bdb5637ca42d6e492dc3bbbad48de"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "metrics" ]
- [ "tracing-log" ]
- ];
- dependencies = {
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; };
- tracing_log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" { inherit profileName; };
- tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" = overridableMkRustCrate (profileName: rec {
- name = "tracing-serde";
- version = "0.1.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1"; };
- dependencies = {
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" = overridableMkRustCrate (profileName: rec {
- name = "tracing-subscriber";
- version = "0.3.16";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "ansi" ]
- [ "default" ]
- [ "env-filter" ]
- [ "fmt" ]
- [ "json" ]
- [ "matchers" ]
- [ "nu-ansi-term" ]
- [ "once_cell" ]
- [ "regex" ]
- [ "registry" ]
- [ "serde" ]
- [ "serde_json" ]
- [ "sharded-slab" ]
- [ "smallvec" ]
- [ "std" ]
- [ "thread_local" ]
- [ "tracing" ]
- [ "tracing-log" ]
- [ "tracing-serde" ]
- ];
- dependencies = {
- matchers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".matchers."0.1.0" { inherit profileName; };
- nu_ansi_term = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nu-ansi-term."0.46.0" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- sharded_slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sharded-slab."0.1.4" { inherit profileName; };
- smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; };
- thread_local = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thread_local."1.1.4" { inherit profileName; };
- tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; };
- tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; };
- tracing_log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" { inherit profileName; };
- tracing_serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" = overridableMkRustCrate (profileName: rec {
- name = "try-lock";
- version = "0.2.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" = overridableMkRustCrate (profileName: rec {
- name = "typenum";
- version = "1.16.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" = overridableMkRustCrate (profileName: rec {
- name = "ucd-trie";
- version = "0.1.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81"; };
- features = builtins.concatLists [
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" = overridableMkRustCrate (profileName: rec {
- name = "unarray";
- version = "0.1.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".unicode-bidi."0.3.8" = overridableMkRustCrate (profileName: rec {
- name = "unicode-bidi";
- version = "0.3.8";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "hardcoded-data" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" = overridableMkRustCrate (profileName: rec {
- name = "unicode-ident";
- version = "1.0.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" = overridableMkRustCrate (profileName: rec {
- name = "unicode-normalization";
- version = "0.1.22";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- dependencies = {
- tinyvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" = overridableMkRustCrate (profileName: rec {
- name = "untrusted";
- version = "0.7.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" = overridableMkRustCrate (profileName: rec {
- name = "url";
- version = "2.3.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "serde" ]
- ];
- dependencies = {
- form_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; };
- idna = rustPackages."registry+https://github.com/rust-lang/crates.io-index".idna."0.3.0" { inherit profileName; };
- percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" = overridableMkRustCrate (profileName: rec {
- name = "urlencoding";
- version = "2.1.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" = overridableMkRustCrate (profileName: rec {
- name = "utoipa";
- version = "3.0.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "3920fa753064b1be7842bea26175ffa0dfc4a8f30bcb52b8ff03fddf8889914c"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "preserve_order" ]
- [ "time" ]
- ];
- dependencies = {
- indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- utoipa_gen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" = overridableMkRustCrate (profileName: rec {
- name = "utoipa-gen";
- version = "3.0.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "720298fac6efca20df9e457e67a1eab41a20d1c3101380b5c4dca1ca60ae0062"; };
- features = builtins.concatLists [
- [ "time" ]
- ];
- dependencies = {
- proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" = overridableMkRustCrate (profileName: rec {
- name = "uuid";
- version = "1.2.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "getrandom" ]
- [ "rng" ]
- [ "serde" ]
- [ "std" ]
- [ "v4" ]
- ];
- dependencies = {
- getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" = overridableMkRustCrate (profileName: rec {
- name = "valuable";
- version = "0.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" = overridableMkRustCrate (profileName: rec {
- name = "vcpkg";
- version = "0.2.15";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" = overridableMkRustCrate (profileName: rec {
- name = "vergen";
- version = "8.0.0-beta.3";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "7ddc80f045ae4afcbb388b085240e773f6728dfbbacff007dd91fc9e2f686fc7"; };
- features = builtins.concatLists [
- [ "cargo" ]
- [ "default" ]
- [ "git" ]
- [ "git2" ]
- [ "git2-rs" ]
- [ "rustc" ]
- [ "rustc_version" ]
- [ "time" ]
- ];
- dependencies = {
- anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; };
- git2_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".git2."0.16.1" { inherit profileName; };
- rustc_version = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { inherit profileName; };
- time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; };
- };
- buildDependencies = {
- rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" = overridableMkRustCrate (profileName: rec {
- name = "version_check";
- version = "0.9.4";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" = overridableMkRustCrate (profileName: rec {
- name = "wait-timeout";
- version = "0.2.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"; };
- dependencies = {
- ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" = overridableMkRustCrate (profileName: rec {
- name = "waker-fn";
- version = "1.1.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" = overridableMkRustCrate (profileName: rec {
- name = "want";
- version = "0.3.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"; };
- dependencies = {
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- try_lock = rustPackages."registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec {
- name = "wasi";
- version = "0.9.0+wasi-snapshot-preview1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec {
- name = "wasi";
- version = "0.11.0+wasi-snapshot-preview1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "std" ]
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen";
- version = "0.2.83";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268"; };
- features = builtins.concatLists [
- [ "default" ]
- [ "spans" ]
- [ "std" ]
- ];
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- wasm_bindgen_macro = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" { profileName = "__noProfile"; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-backend."0.2.83" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen-backend";
- version = "0.2.83";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142"; };
- features = builtins.concatLists [
- [ "spans" ]
- ];
- dependencies = {
- bumpalo = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bumpalo."3.12.0" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-futures."0.4.33" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen-futures";
- version = "0.4.33";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d"; };
- dependencies = {
- cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; };
- js_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; };
- wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; };
- ${ if builtins.elem "atomics" hostPlatformFeatures then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen-macro";
- version = "0.2.83";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810"; };
- features = builtins.concatLists [
- [ "spans" ]
- ];
- dependencies = {
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- wasm_bindgen_macro_support = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen-macro-support";
- version = "0.2.83";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c"; };
- features = builtins.concatLists [
- [ "spans" ]
- ];
- dependencies = {
- proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; };
- quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; };
- syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; };
- wasm_bindgen_backend = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-backend."0.2.83" { inherit profileName; };
- wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" = overridableMkRustCrate (profileName: rec {
- name = "wasm-bindgen-shared";
- version = "0.2.83";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" = overridableMkRustCrate (profileName: rec {
- name = "web-sys";
- version = "0.3.60";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f"; };
- features = builtins.concatLists [
- [ "Blob" ]
- [ "BlobPropertyBag" ]
- [ "Crypto" ]
- [ "Event" ]
- [ "EventTarget" ]
- [ "File" ]
- [ "FormData" ]
- [ "Headers" ]
- [ "MessageEvent" ]
- [ "ReadableStream" ]
- [ "Request" ]
- [ "RequestCredentials" ]
- [ "RequestInit" ]
- [ "RequestMode" ]
- [ "Response" ]
- [ "ServiceWorkerGlobalScope" ]
- [ "Window" ]
- [ "Worker" ]
- [ "WorkerGlobalScope" ]
- ];
- dependencies = {
- js_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; };
- wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" = overridableMkRustCrate (profileName: rec {
- name = "webpki";
- version = "0.22.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"; };
- features = builtins.concatLists [
- [ "alloc" ]
- [ "std" ]
- ];
- dependencies = {
- ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; };
- untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" = overridableMkRustCrate (profileName: rec {
- name = "webpki-roots";
- version = "0.22.6";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87"; };
- dependencies = {
- webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" = overridableMkRustCrate (profileName: rec {
- name = "winapi";
- version = "0.3.9";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"; };
- features = builtins.concatLists [
- [ "consoleapi" ]
- [ "errhandlingapi" ]
- [ "fileapi" ]
- [ "handleapi" ]
- [ "impl-debug" ]
- [ "impl-default" ]
- [ "minwinbase" ]
- [ "minwindef" ]
- [ "ntsecapi" ]
- [ "ntstatus" ]
- [ "processenv" ]
- [ "std" ]
- [ "timezoneapi" ]
- [ "winbase" ]
- [ "wincon" ]
- [ "winerror" ]
- [ "winnt" ]
- [ "winreg" ]
- [ "ws2ipdef" ]
- [ "ws2tcpip" ]
- [ "wtypesbase" ]
- ];
- dependencies = {
- ${ if hostPlatform.config == "i686-pc-windows-gnu" then "winapi_i686_pc_windows_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-i686-pc-windows-gnu."0.4.0" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-gnu" then "winapi_x86_64_pc_windows_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".winapi-i686-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "winapi-i686-pc-windows-gnu";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" = overridableMkRustCrate (profileName: rec {
- name = "winapi-util";
- version = "0.1.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"; };
- dependencies = {
- ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec {
- name = "winapi-x86_64-pc-windows-gnu";
- version = "0.4.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" = overridableMkRustCrate (profileName: rec {
- name = "windows";
- version = "0.43.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"; };
- features = builtins.concatLists [
- [ "Win32" ]
- [ "Win32_Foundation" ]
- [ "Win32_System" ]
- [ "Win32_System_SystemInformation" ]
- [ "default" ]
- ];
- dependencies = {
- ${ if hostPlatform.config == "aarch64-pc-windows-gnullvm" then "windows_aarch64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "aarch64-pc-windows-msvc" || hostPlatform.config == "aarch64-uwp-windows-msvc" then "windows_aarch64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "i686-pc-windows-gnu" || hostPlatform.config == "i686-uwp-windows-gnu" then "windows_i686_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "i686-pc-windows-msvc" || hostPlatform.config == "i686-uwp-windows-msvc" then "windows_i686_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-gnu" || hostPlatform.config == "x86_64-uwp-windows-gnu" then "windows_x86_64_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-gnullvm" then "windows_x86_64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" = overridableMkRustCrate (profileName: rec {
- name = "windows-sys";
- version = "0.42.0";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"; };
- features = builtins.concatLists [
- [ "Win32" ]
- [ "Win32_Foundation" ]
- [ "Win32_Networking" ]
- [ "Win32_Networking_WinSock" ]
- [ "Win32_Security" ]
- [ "Win32_Security_Authentication" ]
- [ "Win32_Security_Authentication_Identity" ]
- [ "Win32_Security_Authorization" ]
- [ "Win32_Security_Credentials" ]
- [ "Win32_Security_Cryptography" ]
- [ "Win32_Storage" ]
- [ "Win32_Storage_FileSystem" ]
- [ "Win32_System" ]
- [ "Win32_System_Console" ]
- [ "Win32_System_IO" ]
- [ "Win32_System_LibraryLoader" ]
- [ "Win32_System_Memory" ]
- [ "Win32_System_Pipes" ]
- [ "Win32_System_SystemServices" ]
- [ "Win32_System_WindowsProgramming" ]
- [ "default" ]
- ];
- dependencies = {
- ${ if hostPlatform.config == "aarch64-pc-windows-gnullvm" then "windows_aarch64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "aarch64-pc-windows-msvc" || hostPlatform.config == "aarch64-uwp-windows-msvc" then "windows_aarch64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "i686-pc-windows-gnu" || hostPlatform.config == "i686-uwp-windows-gnu" then "windows_i686_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "i686-pc-windows-msvc" || hostPlatform.config == "i686-uwp-windows-msvc" then "windows_i686_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-gnu" || hostPlatform.config == "x86_64-uwp-windows-gnu" then "windows_x86_64_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-gnullvm" then "windows_x86_64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" { inherit profileName; };
- ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_aarch64_gnullvm";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_aarch64_msvc";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_i686_gnu";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_i686_msvc";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_x86_64_gnu";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_x86_64_gnullvm";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec {
- name = "windows_x86_64_msvc";
- version = "0.42.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"; };
- });
- "registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" = overridableMkRustCrate (profileName: rec {
- name = "winreg";
- version = "0.10.1";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"; };
- dependencies = {
- winapi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".wiremock."0.5.17" = overridableMkRustCrate (profileName: rec {
- name = "wiremock";
- version = "0.5.17";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "12316b50eb725e22b2f6b9c4cbede5b7b89984274d113a7440c86e5c3fc6f99b"; };
- dependencies = {
- assert_json_diff = rustPackages."registry+https://github.com/rust-lang/crates.io-index".assert-json-diff."2.0.2" { inherit profileName; };
- async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; };
- base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; };
- deadpool = rustPackages."registry+https://github.com/rust-lang/crates.io-index".deadpool."0.9.5" { inherit profileName; };
- futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; };
- futures_timer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-timer."3.0.2" { inherit profileName; };
- http_types = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-types."2.12.0" { inherit profileName; };
- hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; };
- log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; };
- once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; };
- regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; };
- serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; };
- serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; };
- tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" = overridableMkRustCrate (profileName: rec {
- name = "xmlparser";
- version = "0.13.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "4d25c75bf9ea12c4040a97f829154768bbbce366287e2dc044af160cd79a13fd"; };
- features = builtins.concatLists [
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std")
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" = overridableMkRustCrate (profileName: rec {
- name = "yaml-rust";
- version = "0.4.5";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"; };
- dependencies = {
- linked_hash_map = rustPackages."registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" = overridableMkRustCrate (profileName: rec {
- name = "zeroize";
- version = "1.5.7";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f"; };
- features = builtins.concatLists [
- [ "alloc" ]
- (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default")
- ];
- });
- "registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec {
- name = "zstd";
- version = "0.12.2+zstd.1.5.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "e9262a83dc741c0b0ffec209881b45dbc232c21b02a2b9cb1adb93266e41303d"; };
- features = builtins.concatLists [
- [ "arrays" ]
- [ "default" ]
- [ "legacy" ]
- [ "zdict_builder" ]
- ];
- dependencies = {
- zstd_safe = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec {
- name = "zstd-safe";
- version = "6.0.2+zstd.1.5.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "a6cf39f730b440bab43da8fb5faf5f254574462f73f260f85f7987f32154ff17"; };
- features = builtins.concatLists [
- [ "arrays" ]
- [ "legacy" ]
- [ "std" ]
- [ "zdict_builder" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- zstd_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" { inherit profileName; };
- };
- });
- "registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" = overridableMkRustCrate (profileName: rec {
- name = "zstd-sys";
- version = "2.0.5+zstd.1.5.2";
- registry = "registry+https://github.com/rust-lang/crates.io-index";
- src = fetchCratesIo { inherit name version; sha256 = "edc50ffce891ad571e9f9afe5039c4837bede781ac4bb13052ed7ae695518596"; };
- features = builtins.concatLists [
- [ "legacy" ]
- [ "std" ]
- [ "zdict_builder" ]
- ];
- dependencies = {
- libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; };
- };
- buildDependencies = {
- cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; };
- pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; };
- };
- });
-}
\ No newline at end of file
diff --git a/flake.lock b/flake.lock
index 1c0c93e34bd..6f955108475 100644
--- a/flake.lock
+++ b/flake.lock
@@ -71,21 +71,6 @@
"type": "github"
}
},
- "flake-utils_2": {
- "locked": {
- "lastModified": 1659877975,
- "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
- "owner": "numtide",
- "repo": "flake-utils",
- "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
- "type": "github"
- },
- "original": {
- "owner": "numtide",
- "repo": "flake-utils",
- "type": "github"
- }
- },
"nixpkgs": {
"locked": {
"lastModified": 1654275867,
@@ -138,11 +123,11 @@
},
"nixpkgs_3": {
"locked": {
- "lastModified": 1665296151,
- "narHash": "sha256-uOB0oxqxN9K7XGF1hcnY+PQnlQJ+3bP2vCn/+Ru/bbc=",
+ "lastModified": 1718428119,
+ "narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "14ccaaedd95a488dd7ae142757884d8e125b3363",
+ "rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
},
"original": {
@@ -187,15 +172,14 @@
},
"rust-overlay_2": {
"inputs": {
- "flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_3"
},
"locked": {
- "lastModified": 1676601131,
- "narHash": "sha256-iwCg6NimjD4euquhicmSo0wuyP56xUVJUMe0yqUyQms=",
+ "lastModified": 1726626348,
+ "narHash": "sha256-sYV7e1B1yLcxo8/h+/hTwzZYmaju2oObNiy5iRI0C30=",
"owner": "oxalica",
"repo": "rust-overlay",
- "rev": "d0dc81ffe8ea09dbf3c07db62a1a057f5319e3ce",
+ "rev": "6fd52ad8bd88f39efb2c999cc971921c2fb9f3a2",
"type": "github"
},
"original": {
diff --git a/flake.nix b/flake.nix
index bd651e042c1..ad3de7e660b 100644
--- a/flake.nix
+++ b/flake.nix
@@ -2,48 +2,41 @@
description = "hyperswitch";
inputs = {
+ nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
+ flake-parts.url = "github:hercules-ci/flake-parts";
+
+ # TODO: Move away from these to https://github.com/juspay/rust-flake
cargo2nix.url = "github:cargo2nix/cargo2nix/release-0.11.0";
rust-overlay.url = "github:oxalica/rust-overlay";
- flake-parts.url = "github:hercules-ci/flake-parts";
- nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
};
- outputs = inputs@{ self, nixpkgs, flake-parts, ... }:
- flake-parts.lib.mkFlake { inherit inputs; } {
- systems = nixpkgs.lib.systems.flakeExposed;
- perSystem = { self', pkgs, system, ... }:
+ outputs = inputs:
+ inputs.flake-parts.lib.mkFlake { inherit inputs; } {
+ systems = inputs.nixpkgs.lib.systems.flakeExposed;
+ perSystem = { self', pkgs, lib, system, ... }:
let
- rustVersion = "1.65.0";
- rustPkgs = pkgs.rustBuilder.makePackageSet {
- inherit rustVersion;
- packageFun = import ./Cargo.nix;
- };
+ cargoToml = lib.importTOML ./Cargo.toml;
+ rustVersion = cargoToml.workspace.package.rust-version;
frameworks = pkgs.darwin.apple_sdk.frameworks;
in
{
- _module.args.pkgs = import nixpkgs {
+ _module.args.pkgs = import inputs.nixpkgs {
inherit system;
overlays = [ inputs.cargo2nix.overlays.default (import inputs.rust-overlay) ];
};
- packages = rec {
- router = (rustPkgs.workspace.router { }).bin;
- default = router;
- };
- apps = {
- router-scheduler = {
- type = "app";
- program = "${self'.packages.router}/bin/scheduler";
- };
- };
devShells.default = pkgs.mkShell {
- buildInputs = with pkgs; [
+ name = "hyperswitch-shell";
+ packages = with pkgs; [
openssl
pkg-config
exa
fd
rust-bin.stable.${rustVersion}.default
- ] ++ lib.optionals stdenv.isDarwin [ frameworks.CoreServices frameworks.Foundation ]; # arch might have issue finding these libs.
-
+ ] ++ lib.optionals stdenv.isDarwin [
+ # arch might have issue finding these libs.
+ frameworks.CoreServices
+ frameworks.Foundation
+ ];
};
};
};
| 2024-09-11T19:50:00Z | Resolves #5876
This PR makes sure that `flake.nix` builds, and checks it in CI (uses self-hosted runners) going forward. It removes no longer used Nix code (they don't build).
- [x] Add github workflow action to build flake outputs
- [x] Remove packages that no longer build (see #5017) | 3ddfe53838c6b039dc5f669ccd23d3035521d691 | [
"Cargo.nix",
"flake.lock",
"flake.nix"
] | ||
juspay/hyperswitch | juspay__hyperswitch-5862 | Bug: [REFACTOR] unify locker api function call
Create a single method using which locker api can be called and deserialised to the given type. Also send tenant-id in headers | diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 996224d7bea..e2c2dbb48ce 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -4486,7 +4486,7 @@ async fn locker_recipient_create_call(
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
- let store_resp = cards::call_to_locker_hs(
+ let store_resp = cards::add_card_to_hs_locker(
state,
&payload,
&cust_id,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index c22465c3a32..7fc3e9a9559 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -124,6 +124,8 @@ pub enum VaultError {
SaveCardFailed,
#[error("Failed to fetch card details from card vault")]
FetchCardFailed,
+ #[error("Failed to delete card in card vault")]
+ DeleteCardFailed,
#[error("Failed to encode card vault request")]
RequestEncodingFailed,
#[error("Failed to deserialize card vault response")]
@@ -146,6 +148,8 @@ pub enum VaultError {
SavePaymentMethodFailed,
#[error("Failed to generate fingerprint")]
GenerateFingerprintFailed,
+ #[error("Failed while calling locker API")]
+ ApiError,
}
#[derive(Debug, thiserror::Error)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index ccd64f066df..376faeb6464 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -28,8 +28,10 @@ use common_utils::{
consts,
crypto::{self, Encryptable},
encryption::Encryption,
- ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
- generate_id, id_type, type_name,
+ ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt},
+ generate_id, id_type,
+ request::Request,
+ type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
@@ -93,7 +95,7 @@ use crate::{
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::ForeignTryFrom,
},
- utils::{ConnectorResponseExt, OptionExt},
+ utils::OptionExt,
};
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -1876,7 +1878,7 @@ pub async fn add_bank_to_locker(
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
- let store_resp = call_to_locker_hs(
+ let store_resp = add_card_to_hs_locker(
state,
&payload,
customer_id,
@@ -1920,7 +1922,7 @@ pub async fn add_card_to_locker(
card_reference,
)
.await
- .inspect_err(|error| {
+ .inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
&metrics::CONTEXT,
1,
@@ -1929,7 +1931,6 @@ pub async fn add_card_to_locker(
router_env::opentelemetry::KeyValue::new("operation", "add"),
],
);
- logger::error!(?error, "Failed to add card in locker");
})
},
&metrics::CARD_ADD_TIME,
@@ -1962,7 +1963,7 @@ pub async fn get_card_from_locker(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card from hyperswitch card vault")
- .inspect_err(|error| {
+ .inspect_err(|_| {
metrics::CARD_LOCKER_FAILURES.add(
&metrics::CONTEXT,
1,
@@ -1971,7 +1972,6 @@ pub async fn get_card_from_locker(
router_env::opentelemetry::KeyValue::new("operation", "get"),
],
);
- logger::error!(?error, "Failed to retrieve card from locker");
})
},
&metrics::CARD_GET_TIME,
@@ -1996,9 +1996,15 @@ pub async fn delete_card_from_locker(
async move {
delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference)
.await
- .inspect_err(|error| {
- metrics::CARD_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]);
- logger::error!(?error, "Failed to delete card from locker");
+ .inspect_err(|_| {
+ metrics::CARD_LOCKER_FAILURES.add(
+ &metrics::CONTEXT,
+ 1,
+ &[
+ router_env::opentelemetry::KeyValue::new("locker", "rust"),
+ router_env::opentelemetry::KeyValue::new("operation", "delete"),
+ ],
+ );
})
},
&metrics::CARD_DELETE_TIME,
@@ -2006,6 +2012,8 @@ pub async fn delete_card_from_locker(
&[],
)
.await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while deleting card from locker")
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
@@ -2049,7 +2057,8 @@ pub async fn add_card_hs(
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
- let store_card_payload = call_to_locker_hs(state, &payload, customer_id, locker_choice).await?;
+ let store_card_payload =
+ add_card_to_hs_locker(state, &payload, customer_id, locker_choice).await?;
let payment_method_resp = payment_methods::mk_add_card_response_hs(
card.clone(),
@@ -2111,30 +2120,22 @@ pub async fn get_payment_method_from_hs_locker<'a>(
merchant_id,
payment_method_reference,
locker_choice,
+ state.tenant.name.clone(),
+ state.request_id,
)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)
.attach_printable("Making get payment method request failed")?;
- let response = services::call_connector_api(state, request, "add_card_to_locker")
- .await
- .change_context(errors::VaultError::FetchPaymentMethodFailed)
- .attach_printable("Failed while executing call_connector_api for get_card");
- let jwe_body: services::JweBody = response
- .get_response_inner("JweBody")
- .change_context(errors::VaultError::FetchPaymentMethodFailed)?;
- let decrypted_payload = payment_methods::get_decrypted_response_payload(
- jwekey,
- jwe_body,
+
+ let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
+ state,
+ request,
+ "get_pm_from_locker",
locker_choice,
- locker.decryption_scheme.clone(),
)
.await
- .change_context(errors::VaultError::FetchPaymentMethodFailed)
- .attach_printable("Error getting decrypted response payload for get card")?;
- let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload
- .parse_struct("RetrieveCardResp")
- .change_context(errors::VaultError::FetchPaymentMethodFailed)
- .attach_printable("Failed to parse struct to RetrieveCardResp")?;
+ .change_context(errors::VaultError::FetchPaymentMethodFailed)?;
+
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
@@ -2158,7 +2159,7 @@ pub async fn get_payment_method_from_hs_locker<'a>(
}
#[instrument(skip_all)]
-pub async fn call_to_locker_hs(
+pub async fn add_card_to_hs_locker(
state: &routes::SessionState,
payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
@@ -2168,30 +2169,23 @@ pub async fn call_to_locker_hs(
let jwekey = state.conf.jwekey.get_inner();
let db = &*state.store;
let stored_card_response = if !locker.mock_locker {
- let request =
- payment_methods::mk_add_locker_request_hs(jwekey, locker, payload, locker_choice)
- .await?;
- let response = services::call_connector_api(state, request, "add_card_to_hs_locker")
- .await
- .change_context(errors::VaultError::SaveCardFailed);
-
- let jwe_body: services::JweBody = response
- .get_response_inner("JweBody")
- .change_context(errors::VaultError::FetchCardFailed)?;
-
- let decrypted_payload = payment_methods::get_decrypted_response_payload(
+ let request = payment_methods::mk_add_locker_request_hs(
jwekey,
- jwe_body,
+ locker,
+ payload,
+ locker_choice,
+ state.tenant.name.clone(),
+ state.request_id,
+ )
+ .await?;
+ call_locker_api::<payment_methods::StoreCardResp>(
+ state,
+ request,
+ "add_card_to_hs_locker",
Some(locker_choice),
- locker.decryption_scheme.clone(),
)
.await
- .change_context(errors::VaultError::SaveCardFailed)
- .attach_printable("Error getting decrypted response payload")?;
- let stored_card_resp: payment_methods::StoreCardResp = decrypted_payload
- .parse_struct("StoreCardResp")
- .change_context(errors::VaultError::ResponseDeserializationFailed)?;
- stored_card_resp
+ .change_context(errors::VaultError::SaveCardFailed)?
} else {
let card_id = generate_id(consts::ID_LENGTH, "card");
mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await?
@@ -2204,6 +2198,61 @@ pub async fn call_to_locker_hs(
Ok(stored_card)
}
+#[instrument(skip_all)]
+pub async fn call_locker_api<T>(
+ state: &routes::SessionState,
+ request: Request,
+ flow_name: &str,
+ locker_choice: Option<api_enums::LockerChoice>,
+) -> errors::CustomResult<T, errors::VaultError>
+where
+ T: serde::de::DeserializeOwned,
+{
+ let locker = &state.conf.locker;
+ let jwekey = state.conf.jwekey.get_inner();
+ let response_type_name = type_name!(T);
+
+ let response = services::call_connector_api(state, request, flow_name)
+ .await
+ .change_context(errors::VaultError::ApiError)?;
+
+ let is_locker_call_succeeded = response.is_ok();
+
+ let jwe_body = response
+ .unwrap_or_else(|err| err)
+ .response
+ .parse_struct::<services::JweBody>("JweBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed while parsing locker response into JweBody")?;
+
+ let decrypted_payload = payment_methods::get_decrypted_response_payload(
+ jwekey,
+ jwe_body,
+ locker_choice,
+ locker.decryption_scheme.clone(),
+ )
+ .await
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed while decrypting locker payload response")?;
+
+ // Irrespective of locker's response status, payload is JWE + JWS decrypted. But based on locker's status,
+ // if Ok, deserialize the decrypted payload into given type T
+ // if Err, raise an error including locker error message too
+ if is_locker_call_succeeded {
+ let stored_card_resp: Result<T, error_stack::Report<errors::VaultError>> =
+ decrypted_payload
+ .parse_struct(response_type_name)
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable_lazy(|| {
+ format!("Failed while parsing locker response into {response_type_name}")
+ });
+ stored_card_resp
+ } else {
+ Err::<T, error_stack::Report<errors::VaultError>>((errors::VaultError::ApiError).into())
+ .attach_printable_lazy(|| format!("Locker error response: {decrypted_payload:?}"))
+ }
+}
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -2322,29 +2371,21 @@ pub async fn get_card_from_hs_locker<'a>(
merchant_id,
card_reference,
Some(locker_choice),
+ state.tenant.name.clone(),
+ state.request_id,
)
.await
.change_context(errors::VaultError::FetchCardFailed)
.attach_printable("Making get card request failed")?;
- let response = services::call_connector_api(state, request, "get_card_from_locker")
- .await
- .change_context(errors::VaultError::FetchCardFailed)
- .attach_printable("Failed while executing call_connector_api for get_card");
- let jwe_body: services::JweBody = response
- .get_response_inner("JweBody")
- .change_context(errors::VaultError::FetchCardFailed)?;
- let decrypted_payload = payment_methods::get_decrypted_response_payload(
- jwekey,
- jwe_body,
+ let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
+ state,
+ request,
+ "get_card_from_locker",
Some(locker_choice),
- locker.decryption_scheme.clone(),
)
.await
- .change_context(errors::VaultError::FetchCardFailed)
- .attach_printable("Error getting decrypted response payload for get card")?;
- let get_card_resp: payment_methods::RetrieveCardResp = decrypted_payload
- .parse_struct("RetrieveCardResp")
- .change_context(errors::VaultError::FetchCardFailed)?;
+ .change_context(errors::VaultError::FetchCardFailed)?;
+
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
@@ -2366,7 +2407,7 @@ pub async fn delete_card_from_hs_locker<'a>(
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
-) -> errors::RouterResult<payment_methods::DeleteCardResp> {
+) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
@@ -2376,35 +2417,26 @@ pub async fn delete_card_from_hs_locker<'a>(
customer_id,
merchant_id,
card_reference,
+ state.tenant.name.clone(),
+ state.request_id,
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+ .change_context(errors::VaultError::DeleteCardFailed)
.attach_printable("Making delete card request failed")?;
if !locker.mock_locker {
- let response = services::call_connector_api(state, request, "delete_card_from_locker")
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while executing call_connector_api for delete card");
- let jwe_body: services::JweBody = response.get_response_inner("JweBody")?;
- let decrypted_payload = payment_methods::get_decrypted_response_payload(
- jwekey,
- jwe_body,
+ call_locker_api::<payment_methods::DeleteCardResp>(
+ state,
+ request,
+ "delete_card_from_locker",
Some(api_enums::LockerChoice::HyperswitchCardVault),
- locker.decryption_scheme.clone(),
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error getting decrypted response payload for delete card")?;
- let delete_card_resp: payment_methods::DeleteCardResp = decrypted_payload
- .parse_struct("DeleteCardResp")
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- Ok(delete_card_resp)
+ .change_context(errors::VaultError::DeleteCardFailed)
} else {
Ok(mock_delete_card_hs(&*state.store, card_reference)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("card_delete_failure_message")?)
+ .change_context(errors::VaultError::DeleteCardFailed)?)
}
}
@@ -4871,6 +4903,10 @@ pub async fn list_customer_payment_method(
let mut filtered_saved_payment_methods_ctx = Vec::new();
for pm in saved_payment_methods.into_iter() {
+ logger::debug!(
+ "Fetching payment method from locker for payment_method_id: {}",
+ pm.id
+ );
let payment_method = pm.payment_method.get_required_value("payment_method")?;
let parent_payment_method_token =
is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index f594feb5954..f01ecffbbb3 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -10,6 +10,7 @@ use common_utils::{
};
use error_stack::ResultExt;
use josekit::jwe;
+use router_env::tracing_actix_web::RequestId;
use serde::{Deserialize, Serialize};
use crate::{
@@ -301,6 +302,8 @@ pub async fn mk_add_locker_request_hs(
locker: &settings::Locker,
payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
+ tenant_id: String,
+ request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
.encode_to_vec()
@@ -319,6 +322,13 @@ pub async fn mk_add_locker_request_hs(
url.push_str("/cards/add");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(headers::X_TENANT_ID, tenant_id.into());
+ if let Some(req_id) = request_id {
+ request.add_header(
+ headers::X_REQUEST_ID,
+ req_id.as_hyphenated().to_string().into(),
+ );
+ }
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -425,6 +435,7 @@ pub fn mk_add_card_response_hs(
todo!()
}
+#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
@@ -432,6 +443,8 @@ pub async fn mk_get_card_request_hs(
merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
+ tenant_id: String,
+ request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
@@ -458,6 +471,14 @@ pub async fn mk_get_card_request_hs(
url.push_str("/cards/retrieve");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(headers::X_TENANT_ID, tenant_id.into());
+ if let Some(req_id) = request_id {
+ request.add_header(
+ headers::X_REQUEST_ID,
+ req_id.as_hyphenated().to_string().into(),
+ );
+ }
+
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -503,6 +524,8 @@ pub async fn mk_delete_card_request_hs(
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &str,
+ tenant_id: String,
+ request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
@@ -527,6 +550,14 @@ pub async fn mk_delete_card_request_hs(
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(headers::X_TENANT_ID, tenant_id.into());
+ if let Some(req_id) = request_id {
+ request.add_header(
+ headers::X_REQUEST_ID,
+ req_id.as_hyphenated().to_string().into(),
+ );
+ }
+
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -539,6 +570,8 @@ pub async fn mk_delete_card_request_hs_by_id(
id: &String,
merchant_id: &id_type::MerchantId,
card_reference: &str,
+ tenant_id: String,
+ request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = id.to_owned();
let card_req_body = CardReqBodyV2 {
@@ -563,6 +596,14 @@ pub async fn mk_delete_card_request_hs_by_id(
url.push_str("/cards/delete");
let mut request = services::Request::new(services::Method::Post, &url);
request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(headers::X_TENANT_ID, tenant_id.into());
+ if let Some(req_id) = request_id {
+ request.add_header(
+ headers::X_REQUEST_ID,
+ req_id.as_hyphenated().to_string().into(),
+ );
+ }
+
request.set_body(RequestContent::Json(Box::new(jwe_payload)));
Ok(request)
}
@@ -641,12 +682,22 @@ pub fn mk_crud_locker_request(
locker: &settings::Locker,
path: &str,
req: api::TokenizePayloadEncrypted,
+ tenant_id: String,
+ request_id: Option<RequestId>,
) -> CustomResult<services::Request, errors::VaultError> {
let mut url = locker.basilisk_host.to_owned();
url.push_str(path);
let mut request = services::Request::new(services::Method::Post, &url);
request.add_default_headers();
request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(headers::X_TENANT_ID, tenant_id.into());
+ if let Some(req_id) = request_id {
+ request.add_header(
+ headers::X_REQUEST_ID,
+ req_id.as_hyphenated().to_string().into(),
+ );
+ }
+
request.set_body(RequestContent::Json(Box::new(req)));
Ok(request)
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 11cb0c11761..035c5c139a8 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -307,7 +307,7 @@ pub async fn save_payout_data_to_locker(
};
// Store payout method in locker
- let stored_resp = cards::call_to_locker_hs(
+ let stored_resp = cards::add_card_to_hs_locker(
state,
&locker_req,
customer_id,
@@ -559,6 +559,7 @@ pub async fn save_payout_data_to_locker(
card_reference,
)
.await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to delete PMD from locker as a part of metadata update operation",
)?;
@@ -566,7 +567,7 @@ pub async fn save_payout_data_to_locker(
locker_req.update_requestor_card_reference(Some(card_reference.to_string()));
// Store in locker
- let stored_resp = cards::call_to_locker_hs(
+ let stored_resp = cards::add_card_to_hs_locker(
state,
&locker_req,
customer_id,
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index ac452233e0f..caa96826937 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -83,6 +83,7 @@ pub mod headers {
pub const BROWSER_NAME: &str = "x-browser-name";
pub const X_CLIENT_PLATFORM: &str = "x-client-platform";
pub const X_MERCHANT_DOMAIN: &str = "x-merchant-domain";
+ pub const X_TENANT_ID: &str = "x-tenant-id";
}
pub mod pii {
| 2024-09-11T14:08:08Z |
## Description
<!-- Describe your changes in detail -->
This PR performs below changes -
* Creates a single method using which locker api can be called and deserialised to the given type.
* Currently, if locker returns an Err, the error response is not JWE+JWS decrypted. Instead its logged directly. This new method calls the api and irrespective of whether locker responds with an OK response or Err response, JWE+JWS decryption happens on the locker response.
* Sends `x-tenant-id` in the headers to locker
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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)?
-->
To test, I failed the locker on purpose and received below error report in Hyperswitch which also includes JWE+JWS decrypted error message.

Sandbox testing - Basic sanity tests which also involves saving card in locker would suffice | 10ac08944986a1fd101f8f05263e92ed7ebbba94 |
To test, I failed the locker on purpose and received below error report in Hyperswitch which also includes JWE+JWS decrypted error message.

Sandbox testing - Basic sanity tests which also involves saving card in locker would suffice
| [
"crates/router/src/core/admin.rs",
"crates/router/src/core/errors.rs",
"crates/router/src/core/payment_methods/cards.rs",
"crates/router/src/core/payment_methods/transformers.rs",
"crates/router/src/core/payouts/helpers.rs",
"crates/router/src/lib.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5860 | Bug: refactor(users): Populate optional fields in the user APIs
Currently
- list users in lineage
- get user role details
- list invitations
APIs send `null` for role_name, entity_name etc...
These fields should be populated with proper data. | diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7bb8409993d..7b22387b3c3 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -188,6 +188,7 @@ pub struct GetUserRoleDetailsResponseV2 {
pub profile: Option<NameIdUnit<String, id_type::ProfileId>>,
pub status: UserStatus,
pub entity_type: EntityType,
+ pub role_name: String,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 22aa80a459a..828dfeb20f8 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -63,5 +63,5 @@ pub enum RoleCheckType {
#[derive(Debug, serde::Serialize, Clone)]
pub struct MinimalRoleInfo {
pub role_id: String,
- pub role_name: Option<String>,
+ pub role_name: String,
}
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 0a3c0e6d42f..065a5b6e114 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -43,6 +43,20 @@ impl Role {
.await
}
+ pub async fn find_by_role_id_in_org_scope(
+ conn: &PgPooledConn,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::role_id
+ .eq(role_id.to_owned())
+ .and(dsl::org_id.eq(org_id.to_owned())),
+ )
+ .await
+ }
+
pub async fn update_by_role_id(
conn: &PgPooledConn,
role_id: &str,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index c9b0a956dbc..a0b6606c227 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -1829,11 +1829,15 @@ pub mod routes {
json_payload.into_inner(),
|state, auth: UserFromToken, req, _| async move {
let role_id = auth.role_id;
- let role_info =
- RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .change_context(OpenSearchError::UnknownError)?;
+ let role_info = RoleInfo::from_role_id_in_merchant_scope(
+ &state,
+ &role_id,
+ &auth.merchant_id,
+ &auth.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)?;
let permissions = role_info.get_permissions_set();
let accessible_indexes: Vec<_> = OPENSEARCH_INDEX_PERMISSIONS
.iter()
@@ -1885,11 +1889,15 @@ pub mod routes {
indexed_req,
|state, auth: UserFromToken, req, _| async move {
let role_id = auth.role_id;
- let role_info =
- RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .change_context(OpenSearchError::UnknownError)?;
+ let role_info = RoleInfo::from_role_id_in_merchant_scope(
+ &state,
+ &role_id,
+ &auth.merchant_id,
+ &auth.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .change_context(OpenSearchError::UnknownError)?;
let permissions = role_info.get_permissions_set();
let _ = OPENSEARCH_INDEX_PERMISSIONS
.iter()
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 31ab0e8ff22..45e9065d263 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -100,7 +100,7 @@ pub async fn get_user_details(
) -> UserResponse<user_api::GetUserDetailsResponse> {
let user = user_from_token.get_user_from_db(&state).await?;
let verification_days_left = utils::user::get_verification_days_left(&state, &user)?;
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -539,7 +539,7 @@ async fn handle_invitation(
.into());
}
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
state,
&request.role_id,
&user_from_token.merchant_id,
@@ -1154,7 +1154,7 @@ pub async fn switch_merchant_id(
let user = user_from_token.get_user_from_db(&state).await?;
let key_manager_state = &(&state).into();
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -1328,10 +1328,15 @@ pub async fn list_merchants_for_user(
return Err(report!(UserErrors::InternalServerError)
.attach_printable("org_id not found in user_role"));
};
- roles::RoleInfo::from_role_id(&state, &user_role.role_id, merchant_id, org_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Unable to find role info for user role")
+ roles::RoleInfo::from_role_id_in_merchant_scope(
+ &state,
+ &user_role.role_id,
+ merchant_id,
+ org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to find role info for user role")
}))
.await?
.into_iter()
@@ -1394,7 +1399,7 @@ pub async fn get_user_details_in_merchant_account(
.to_not_found_response(UserErrors::InvalidRoleOperation)
.attach_printable("User not found in the merchant account")?;
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&required_user_role.role_id,
&user_from_token.merchant_id,
@@ -1428,7 +1433,7 @@ pub async fn list_user_roles_details(
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
- let requestor_role_info = roles::RoleInfo::from_role_id(
+ let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -1438,7 +1443,7 @@ pub async fn list_user_roles_details(
.to_not_found_response(UserErrors::InternalServerError)
.attach_printable("Failed to fetch role info")?;
- let user_roles_set: HashSet<_> = state
+ let user_roles_set = state
.store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: required_user.get_user_id(),
@@ -1459,7 +1464,7 @@ pub async fn list_user_roles_details(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to fetch user roles")?
.into_iter()
- .collect();
+ .collect::<HashSet<_>>();
let org_name = state
.store
@@ -1477,11 +1482,11 @@ pub async fn list_user_roles_details(
let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold(
(Vec::new(), Vec::new()),
|(mut merchant, mut merchant_profile), user_role| {
- let entity_type = user_role
+ let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)
- .attach_printable("Failed to fetch entity id and type")?
- .1;
+ .attach_printable("Failed to compute entity id and type")?;
+
match entity_type {
EntityType::Merchant => {
let merchant_id = user_role
@@ -1525,7 +1530,7 @@ pub async fn list_user_roles_details(
},
)?;
- let merchant_map: HashMap<_, _> = state
+ let merchant_map = state
.store
.list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
.await
@@ -1538,50 +1543,71 @@ pub async fn list_user_roles_details(
merchant_account.merchant_name.clone(),
)
})
- .collect();
+ .collect::<HashMap<_, _>>();
let key_manager_state = &(&state).into();
- let profile_map: HashMap<_, _> =
- futures::future::try_join_all(merchant_profile_ids.iter().map(
- |merchant_profile_id| async {
- let merchant_key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &merchant_profile_id.0,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
+ let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map(
+ |merchant_profile_id| async {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &merchant_profile_id.0,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
- state
- .store
- .find_business_profile_by_profile_id(
- key_manager_state,
- &merchant_key_store,
- &merchant_profile_id.1,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to retrieve business profile")
- },
- ))
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to construct proifle map")?
- .into_iter()
- .map(|profile| (profile.get_id().to_owned(), profile.profile_name))
- .collect();
+ state
+ .store
+ .find_business_profile_by_profile_id(
+ key_manager_state,
+ &merchant_key_store,
+ &merchant_profile_id.1,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to retrieve business profile")
+ },
+ ))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to construct proifle map")?
+ .into_iter()
+ .map(|profile| (profile.get_id().to_owned(), profile.profile_name))
+ .collect::<HashMap<_, _>>();
+
+ let role_name_map = futures::future::try_join_all(
+ user_roles_set
+ .iter()
+ .map(|user_role| user_role.role_id.clone())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .map(|role_id| async {
+ let role_info = roles::RoleInfo::from_role_id_in_org_scope(
+ &state,
+ &role_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok::<_, error_stack::Report<_>>((role_id, role_info.get_role_name().to_string()))
+ }),
+ )
+ .await?
+ .into_iter()
+ .collect::<HashMap<_, _>>();
let role_details_list: Vec<_> = user_roles_set
.iter()
.map(|user_role| {
- let entity_type = user_role
+ let (_, entity_type) = user_role
.get_entity_id_and_type()
- .ok_or(UserErrors::InternalServerError)?
- .1;
+ .ok_or(UserErrors::InternalServerError)?;
+
let (merchant, profile) = match entity_type {
EntityType::Internal => {
return Err(UserErrors::InvalidRoleOperationWithMessage(
@@ -1642,6 +1668,10 @@ pub async fn list_user_roles_details(
profile,
status: user_role.status.foreign_into(),
entity_type,
+ role_name: role_name_map
+ .get(&user_role.role_id)
+ .ok_or(UserErrors::InternalServerError)
+ .cloned()?,
})
})
.collect::<Result<Vec<_>, UserErrors>>()?;
@@ -1684,7 +1714,7 @@ pub async fn list_users_for_merchant_account(
let users_user_roles_and_roles =
futures::future::try_join_all(users_and_user_roles.into_iter().map(
|(user, user_role)| async {
- roles::RoleInfo::from_role_id(
+ roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_role.role_id.clone(),
user_role
@@ -2586,7 +2616,7 @@ pub async fn list_orgs_for_user(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -2640,7 +2670,7 @@ pub async fn list_merchants_for_user_in_org(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListMerchantsForUserInOrgResponse>> {
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -2707,7 +2737,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> {
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -2796,7 +2826,7 @@ pub async fn switch_org_for_user(
.into());
}
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -2875,7 +2905,7 @@ pub async fn switch_merchant_for_user_in_org(
}
let key_manager_state = &(&state).into();
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -3084,7 +3114,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
}
let key_manager_state = &(&state).into();
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 369ee97a02a..868d2e65a24 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -3,9 +3,11 @@ use std::collections::{HashMap, HashSet};
use api_models::{user as user_api, user_role as user_role_api};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
+ organization::OrganizationBridge,
user_role::UserRoleUpdate,
};
use error_stack::{report, ResultExt};
+use masking::Secret;
use once_cell::sync::Lazy;
use crate::{
@@ -75,7 +77,7 @@ pub async fn update_user_role(
req: user_role_api::UpdateUserRoleRequest,
_req_state: ReqState,
) -> UserResponse<()> {
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&req.role_id,
&user_from_token.merchant_id,
@@ -100,7 +102,7 @@ pub async fn update_user_role(
.attach_printable("User Changing their own role");
}
- let updator_role = roles::RoleInfo::from_role_id(
+ let updator_role = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -133,7 +135,7 @@ pub async fn update_user_role(
};
if let Some(user_role) = v2_user_role_to_be_updated {
- let role_to_be_updated = roles::RoleInfo::from_role_id(
+ let role_to_be_updated = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_role.role_id,
&user_from_token.merchant_id,
@@ -198,7 +200,7 @@ pub async fn update_user_role(
};
if let Some(user_role) = v1_user_role_to_be_updated {
- let role_to_be_updated = roles::RoleInfo::from_role_id(
+ let role_to_be_updated = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_role.role_id,
&user_from_token.merchant_id,
@@ -501,7 +503,7 @@ pub async fn delete_user_role(
.attach_printable("User deleting himself");
}
- let deletion_requestor_role_info = roles::RoleInfo::from_role_id(
+ let deletion_requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -535,7 +537,7 @@ pub async fn delete_user_role(
};
if let Some(role_to_be_deleted) = user_role_v2 {
- let target_role_info = roles::RoleInfo::from_role_id(
+ let target_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&role_to_be_deleted.role_id,
&user_from_token.merchant_id,
@@ -597,7 +599,7 @@ pub async fn delete_user_role(
};
if let Some(role_to_be_deleted) = user_role_v1 {
- let target_role_info = roles::RoleInfo::from_role_id(
+ let target_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&role_to_be_deleted.role_id,
&user_from_token.merchant_id,
@@ -672,7 +674,7 @@ pub async fn list_users_in_lineage(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> {
- let requestor_role_info = roles::RoleInfo::from_role_id(
+ let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -744,6 +746,29 @@ pub async fn list_users_in_lineage(
.map(|user| (user.user_id.clone(), user.email))
.collect::<HashMap<_, _>>();
+ let role_info_map =
+ futures::future::try_join_all(user_roles_set.iter().map(|user_role| async {
+ roles::RoleInfo::from_role_id_in_org_scope(
+ &state,
+ &user_role.role_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .map(|role_info| {
+ (
+ user_role.role_id.clone(),
+ user_role_api::role::MinimalRoleInfo {
+ role_id: user_role.role_id.clone(),
+ role_name: role_info.get_role_name().to_string(),
+ },
+ )
+ })
+ }))
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .collect::<HashMap<_, _>>();
+
let user_role_map = user_roles_set
.into_iter()
.fold(HashMap::new(), |mut map, user_role| {
@@ -763,11 +788,13 @@ pub async fn list_users_in_lineage(
.ok_or(UserErrors::InternalServerError)?,
roles: role_id_vec
.into_iter()
- .map(|role_id| user_role_api::role::MinimalRoleInfo {
- role_id,
- role_name: None,
+ .map(|role_id| {
+ role_info_map
+ .get(&role_id)
+ .cloned()
+ .ok_or(UserErrors::InternalServerError)
})
- .collect(),
+ .collect::<Result<Vec<_>, _>>()?,
})
})
.collect::<Result<Vec<_>, _>>()?,
@@ -778,7 +805,7 @@ pub async fn list_invitations_for_user(
state: SessionState,
user_from_token: auth::UserIdFromAuth,
) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> {
- let invitations = state
+ let user_roles = state
.store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
@@ -794,18 +821,143 @@ pub async fn list_invitations_for_user(
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles by user id and invitation sent")?
.into_iter()
- .collect::<HashSet<_>>()
+ .collect::<HashSet<_>>();
+
+ let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold(
+ (Vec::new(), Vec::new(), Vec::new()),
+ |(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| {
+ let (_, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Failed to compute entity id and type")?;
+
+ match entity_type {
+ EntityType::Organization => org_ids.push(
+ user_role
+ .org_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ ),
+ EntityType::Merchant => merchant_ids.push(
+ user_role
+ .merchant_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ ),
+ EntityType::Profile => profile_ids_with_merchant_ids.push((
+ user_role
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ user_role
+ .merchant_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ )),
+ EntityType::Internal => return Err(report!(UserErrors::InternalServerError)),
+ }
+
+ Ok((org_ids, merchant_ids, profile_ids_with_merchant_ids))
+ },
+ )?;
+
+ let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async {
+ let org_name = state
+ .store
+ .find_organization_by_org_id(&org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .get_organization_name()
+ .map(Secret::new);
+
+ Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name))
+ }))
+ .await?
+ .into_iter()
+ .collect::<HashMap<_, _>>();
+
+ let key_manager_state = &(&state).into();
+
+ let merchant_name_map = state
+ .store
+ .list_multiple_merchant_accounts(key_manager_state, merchant_ids)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .map(|merchant| {
+ (
+ merchant.get_id().clone(),
+ merchant
+ .merchant_name
+ .map(|encryptable_name| encryptable_name.into_inner()),
+ )
+ })
+ .collect::<HashMap<_, _>>();
+
+ let master_key = &state.store.get_master_key().to_vec().into();
+
+ let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map(
+ |(profile_id, merchant_id)| async {
+ let merchant_key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let business_profile = state
+ .store
+ .find_business_profile_by_profile_id(
+ key_manager_state,
+ &merchant_key_store,
+ profile_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok::<_, error_stack::Report<UserErrors>>((
+ profile_id.clone(),
+ Secret::new(business_profile.profile_name),
+ ))
+ },
+ ))
+ .await?
+ .into_iter()
+ .collect::<HashMap<_, _>>();
+
+ user_roles
.into_iter()
- .filter_map(|user_role| {
- let (entity_id, entity_type) = user_role.get_entity_id_and_type()?;
- Some(user_role_api::ListInvitationForUserResponse {
+ .map(|user_role| {
+ let (entity_id, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable("Failed to compute entity id and type")?;
+
+ let entity_name = match entity_type {
+ EntityType::Organization => user_role
+ .org_id
+ .as_ref()
+ .and_then(|org_id| org_name_map.get(org_id).cloned())
+ .ok_or(UserErrors::InternalServerError)?,
+ EntityType::Merchant => user_role
+ .merchant_id
+ .as_ref()
+ .and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned())
+ .ok_or(UserErrors::InternalServerError)?,
+ EntityType::Profile => user_role
+ .profile_id
+ .as_ref()
+ .map(|profile_id| profile_name_map.get(profile_id).cloned())
+ .ok_or(UserErrors::InternalServerError)?,
+ EntityType::Internal => return Err(report!(UserErrors::InternalServerError)),
+ };
+
+ Ok(user_role_api::ListInvitationForUserResponse {
entity_id,
entity_type,
- entity_name: None,
+ entity_name,
role_id: user_role.role_id,
})
})
- .collect();
-
- Ok(ApplicationResponse::Json(invitations))
+ .collect::<Result<Vec<_>, _>>()
+ .map(ApplicationResponse::Json)
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 8c9cd1da0ab..571ae7f995d 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -127,7 +127,7 @@ pub async fn get_role_with_groups(
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
&role.role_id,
&user_from_token.merchant_id,
@@ -172,7 +172,7 @@ pub async fn update_role(
utils::user_role::validate_role_groups(groups)?;
}
- let role_info = roles::RoleInfo::from_role_id(
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
role_id,
&user_from_token.merchant_id,
@@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level(
if check_type && role_info.get_entity_type() == req.entity_type {
Some(role_api::MinimalRoleInfo {
role_id: role_info.get_role_id().to_string(),
- role_name: Some(role_info.get_role_name().to_string()),
+ role_name: role_info.get_role_name().to_string(),
})
} else {
None
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 76111afc6bd..42cd71c280d 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3341,6 +3341,16 @@ impl RoleInterface for KafkaStore {
.await
}
+ async fn find_role_by_role_id_in_org_scope(
+ &self,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ self.diesel_store
+ .find_role_by_role_id_in_org_scope(role_id, org_id)
+ .await
+ }
+
async fn update_role_by_role_id(
&self,
role_id: &str,
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index ddcb24dc254..20a4922d165 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -30,6 +30,12 @@ pub trait RoleInterface {
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError>;
+ async fn find_role_by_role_id_in_org_scope(
+ &self,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> CustomResult<storage::Role, errors::StorageError>;
+
async fn update_role_by_role_id(
&self,
role_id: &str,
@@ -93,6 +99,18 @@ impl RoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[instrument(skip_all)]
+ async fn find_role_by_role_id_in_org_scope(
+ &self,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Role::find_by_role_id_in_org_scope(&conn, role_id, org_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
#[instrument(skip_all)]
async fn update_role_by_role_id(
&self,
@@ -223,6 +241,24 @@ impl RoleInterface for MockDb {
)
}
+ async fn find_role_by_role_id_in_org_scope(
+ &self,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> CustomResult<storage::Role, errors::StorageError> {
+ let roles = self.roles.lock().await;
+ roles
+ .iter()
+ .find(|role| role.role_id == role_id && role.org_id == *org_id)
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "No role available in org scope for role_id = {role_id} and org_id = {org_id:?}"
+ ))
+ .into(),
+ )
+ }
+
async fn update_role_by_role_id(
&self,
role_id: &str,
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index c498a33614e..19383f010f2 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -71,7 +71,7 @@ impl RoleInfo {
.any(|group| get_permissions_vec(group).contains(required_permission))
}
- pub async fn from_role_id(
+ pub async fn from_role_id_in_merchant_scope(
state: &SessionState,
role_id: &str,
merchant_id: &id_type::MerchantId,
@@ -87,6 +87,22 @@ impl RoleInfo {
.map(Self::from)
}
}
+
+ pub async fn from_role_id_in_org_scope(
+ state: &SessionState,
+ role_id: &str,
+ org_id: &id_type::OrganizationId,
+ ) -> CustomResult<Self, errors::StorageError> {
+ if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
+ Ok(role.clone())
+ } else {
+ state
+ .store
+ .find_role_by_role_id_in_org_scope(role_id, org_id)
+ .await
+ .map(Self::from)
+ }
+ }
}
impl From<diesel_models::role::Role> for RoleInfo {
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 3da24f2be7d..22edf6768c8 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -75,9 +75,14 @@ impl UserFromToken {
}
pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> {
- RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
- .await
- .change_context(UserErrors::InternalServerError)
+ RoleInfo::from_role_id_in_merchant_scope(
+ state,
+ &self.role_id,
+ &self.merchant_id,
+ &self.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
}
}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 68bee0f022d..2d700ffe505 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -152,10 +152,11 @@ pub async fn set_role_permissions_in_cache_if_required(
return Ok(());
}
- let role_info = roles::RoleInfo::from_role_id(state, role_id, merchant_id, org_id)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Error getting role_info from role_id")?;
+ let role_info =
+ roles::RoleInfo::from_role_id_in_merchant_scope(state, role_id, merchant_id, org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Error getting role_info from role_id")?;
authz::set_role_info_in_cache(
state,
| 2024-09-11T12:21:48Z |
## Description
<!-- Describe your changes in detail -->
- Populate entity name in list invitations API.
- Add role name in the response of get user role details API.
- Populate role name in list users in lineage API.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5860.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. List invitations
```
curl 'http://localhost:8080/user/list/invitation' \
-H 'authorization: Bearer SPT with accept invite purpose' \
```
```json
[
{
"entity_id": "merchant_1726053750",
"entity_type": "merchant",
"entity_name": "First Merchant",
"role_id": "role_66NmyEPLz3vHvN67Wdz1"
},
{
"entity_id": "merchant_1726053866",
"entity_type": "merchant",
"entity_name": "Second merchant",
"role_id": "role_pit0nT2xUJsZPCPUqOJD"
}
]
```
Entity name should be populated.
2. List lineage
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
```json
[
{
"email": "mani.dchandra+secmer@juspay.in",
"roles": [
{
"role_id": "role_pit0nT2xUJsZPCPUqOJD",
"role_name": "role_in_second_merchant"
},
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"role_name": "role_in_first_merchant"
}
]
},
{
"email": "mani.dchandra+firmer@juspay.in",
"roles": [
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"role_name": "role_in_first_merchant"
}
]
},
{
"email": "mani.dchandra@juspay.in",
"roles": [
{
"role_id": "org_admin",
"role_name": "organization_admin"
}
]
}
]
```
Role name should be populated.
3. Get user role details
```
curl 'http://localhost:8080/user/user/v2' \
-H 'authorization: Bearer JWT' \
--data-raw '{"email":"email"}'
```
```
[
{
"role_id": "role_pit0nT2xUJsZPCPUqOJD",
"org": {
"name": null,
"id": "org_UQ9eMA5oT6GjJMONxPtZ"
},
"merchant": {
"name": "Second merchant",
"id": "merchant_1726053866"
},
"profile": null,
"status": "Active",
"entity_type": "merchant",
"role_name": "role_in_second_merchant"
},
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"org": {
"name": null,
"id": "org_UQ9eMA5oT6GjJMONxPtZ"
},
"merchant": {
"name": "First Profile",
"id": "merchant_1726053750"
},
"profile": null,
"status": "Active",
"entity_type": "merchant",
"role_name": "role_in_first_merchant"
}
]
```
`role_name` should be present and populated. | 246fdc84064367885596b33f5e0e66af78a97a3c |
1. List invitations
```
curl 'http://localhost:8080/user/list/invitation' \
-H 'authorization: Bearer SPT with accept invite purpose' \
```
```json
[
{
"entity_id": "merchant_1726053750",
"entity_type": "merchant",
"entity_name": "First Merchant",
"role_id": "role_66NmyEPLz3vHvN67Wdz1"
},
{
"entity_id": "merchant_1726053866",
"entity_type": "merchant",
"entity_name": "Second merchant",
"role_id": "role_pit0nT2xUJsZPCPUqOJD"
}
]
```
Entity name should be populated.
2. List lineage
```
curl 'http://localhost:8080/user/user/v2/list' \
-H 'authorization: Bearer JWT' \
```
```json
[
{
"email": "mani.dchandra+secmer@juspay.in",
"roles": [
{
"role_id": "role_pit0nT2xUJsZPCPUqOJD",
"role_name": "role_in_second_merchant"
},
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"role_name": "role_in_first_merchant"
}
]
},
{
"email": "mani.dchandra+firmer@juspay.in",
"roles": [
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"role_name": "role_in_first_merchant"
}
]
},
{
"email": "mani.dchandra@juspay.in",
"roles": [
{
"role_id": "org_admin",
"role_name": "organization_admin"
}
]
}
]
```
Role name should be populated.
3. Get user role details
```
curl 'http://localhost:8080/user/user/v2' \
-H 'authorization: Bearer JWT' \
--data-raw '{"email":"email"}'
```
```
[
{
"role_id": "role_pit0nT2xUJsZPCPUqOJD",
"org": {
"name": null,
"id": "org_UQ9eMA5oT6GjJMONxPtZ"
},
"merchant": {
"name": "Second merchant",
"id": "merchant_1726053866"
},
"profile": null,
"status": "Active",
"entity_type": "merchant",
"role_name": "role_in_second_merchant"
},
{
"role_id": "role_66NmyEPLz3vHvN67Wdz1",
"org": {
"name": null,
"id": "org_UQ9eMA5oT6GjJMONxPtZ"
},
"merchant": {
"name": "First Profile",
"id": "merchant_1726053750"
},
"profile": null,
"status": "Active",
"entity_type": "merchant",
"role_name": "role_in_first_merchant"
}
]
```
`role_name` should be present and populated.
| [
"crates/api_models/src/user.rs",
"crates/api_models/src/user_role/role.rs",
"crates/diesel_models/src/query/role.rs",
"crates/router/src/analytics.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/db/kafka_store... | |
juspay/hyperswitch | juspay__hyperswitch-5855 | Bug: fix merchant payment method list
1. `collect_billing_details_from_wallets` field should be made true if either of `always_collect_billing_details_from_wallet_connector` ` collect_billing_details_from_wallet_connector`
2. `collect_shipping_details_from_wallets` field should be made true if either of `always_collect_shipping_details_from_wallet_connector` ` collect_shipping_details_from_wallet_connector` | diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c553840347d..8ab3bf50147 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3656,23 +3656,29 @@ pub async fn list_payment_methods(
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
- let collect_shipping_details_from_wallets = business_profile
- .as_ref()
- .and_then(|business_profile| {
- business_profile.always_collect_shipping_details_from_wallet_connector
- })
- .or(business_profile.as_ref().and_then(|business_profile| {
- business_profile.collect_shipping_details_from_wallet_connector
- }));
+ let collect_shipping_details_from_wallets =
+ business_profile.as_ref().and_then(|business_profile| {
+ if business_profile
+ .always_collect_shipping_details_from_wallet_connector
+ .unwrap_or(false)
+ {
+ business_profile.always_collect_shipping_details_from_wallet_connector
+ } else {
+ business_profile.collect_shipping_details_from_wallet_connector
+ }
+ });
- let collect_billing_details_from_wallets = business_profile
- .as_ref()
- .and_then(|business_profile| {
- business_profile.always_collect_billing_details_from_wallet_connector
- })
- .or(business_profile.as_ref().and_then(|business_profile| {
- business_profile.collect_billing_details_from_wallet_connector
- }));
+ let collect_billing_details_from_wallets =
+ business_profile.as_ref().and_then(|business_profile| {
+ if business_profile
+ .always_collect_billing_details_from_wallet_connector
+ .unwrap_or(false)
+ {
+ business_profile.always_collect_billing_details_from_wallet_connector
+ } else {
+ business_profile.collect_billing_details_from_wallet_connector
+ }
+ });
let is_tax_connector_enabled = business_profile.as_ref().map_or(false, |business_profile| {
business_profile.get_is_tax_connector_enabled()
| 2024-09-11T08:13:26Z |
## Description
<!-- Describe your changes in detail -->
1. `collect_billing_details_from_wallets` field should be made true if either of `always_collect_billing_details_from_wallet_connector` ` collect_billing_details_from_wallet_connector` is true
2. `collect_shipping_details_from_wallets` field should be made true if either of `always_collect_shipping_details_from_wallet_connector` ` collect_shipping_details_from_wallet_connector` is true
So that the sdk gets to know that the address details needs to be collected from apple pay and not from the customers
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account and mca
-> Set the below config in the business profile
```
curl --location 'http://localhost:8080/account/merchant_1726040867/business_profile/pro_a6nz5AzJNeeczSAq4bjx' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_billing_details_from_wallet_connector": true,
"collect_shipping_details_from_wallet_connector": true,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": true
}'
```
-> Do merchant payment methods list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_TmMtZnKNBJ9k42xukGoq_secret_xMznqubrJIb6UDS16dAC' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cfcaee79a88d488c8bc71a50d39010ef'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
```
In the above response `"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,` even though the ` "always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,` is set to false.
-> When all the configs are false
```
curl --location 'http://localhost:8080/account/merchant_1726047949/business_profile/pro_TAHURhBV24jEzIvGiIiQ' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
}'
```
-> merchant pml
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false
}
```
-> When ` "always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,`
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
``` | be346e5d963925ecbe1bbb77aa024f7eed66019e |
-> Create a merchant account and mca
-> Set the below config in the business profile
```
curl --location 'http://localhost:8080/account/merchant_1726040867/business_profile/pro_a6nz5AzJNeeczSAq4bjx' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_billing_details_from_wallet_connector": true,
"collect_shipping_details_from_wallet_connector": true,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
"is_connector_agnostic_mit_enabled": true
}'
```
-> Do merchant payment methods list
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_TmMtZnKNBJ9k42xukGoq_secret_xMznqubrJIb6UDS16dAC' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cfcaee79a88d488c8bc71a50d39010ef'
```
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
```
In the above response `"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,` even though the ` "always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,` is set to false.
-> When all the configs are false
```
curl --location 'http://localhost:8080/account/merchant_1726047949/business_profile/pro_TAHURhBV24jEzIvGiIiQ' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_billing_details_from_wallet_connector": false,
"collect_shipping_details_from_wallet_connector": false,
"always_collect_shipping_details_from_wallet_connector": false,
"always_collect_billing_details_from_wallet_connector": false,
}'
```
-> merchant pml
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false
}
```
-> When ` "always_collect_shipping_details_from_wallet_connector": true,
"always_collect_billing_details_from_wallet_connector": true,`
```
{
"redirect_url": "https://google.com/success",
"currency": "EUR",
"payment_methods": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
},
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"shipping.address.city": {
"required_field": "shipping.address.city",
"display_name": "city",
"field_type": "user_shipping_address_city",
"value": null
},
"shipping.address.last_name": {
"required_field": "shipping.address.last_name",
"display_name": "shipping_last_name",
"field_type": "user_shipping_name",
"value": null
},
"shipping.address.first_name": {
"required_field": "shipping.address.first_name",
"display_name": "shipping_first_name",
"field_type": "user_shipping_name",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": null
},
"shipping.address.line1": {
"required_field": "shipping.address.line1",
"display_name": "line1",
"field_type": "user_shipping_address_line1",
"value": null
},
"shipping.address.state": {
"required_field": "shipping.address.state",
"display_name": "state",
"field_type": "user_shipping_address_state",
"value": null
},
"shipping.address.country": {
"required_field": "shipping.address.country",
"display_name": "country",
"field_type": {
"user_shipping_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"shipping.address.zip": {
"required_field": "shipping.address.zip",
"display_name": "zip",
"field_type": "user_shipping_address_pincode",
"value": null
},
"billing.address.line2": {
"required_field": "payment_method_data.billing.address.line2",
"display_name": "line2",
"field_type": "user_address_line2",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cybersource"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": null,
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "DinersClub",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"cybersource"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.last_name": {
"required_field": "payment_method_data.billing.address.last_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.line1": {
"required_field": "payment_method_data.billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": null
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.first_name": {
"required_field": "payment_method_data.billing.address.first_name",
"display_name": "card_holder_name",
"field_type": "user_full_name",
"value": null
},
"billing.address.city": {
"required_field": "payment_method_data.billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": null
},
"billing.email": {
"required_field": "payment_method_data.billing.email",
"display_name": "email",
"field_type": "user_email_address",
"value": null
},
"billing.address.state": {
"required_field": "payment_method_data.billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": null
},
"billing.address.zip": {
"required_field": "payment_method_data.billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": null
},
"billing.address.country": {
"required_field": "payment_method_data.billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": true,
"collect_billing_details_from_wallets": true,
"is_tax_calculation_enabled": false
}
```
| [
"crates/router/src/core/payment_methods/cards.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5852 | Bug: Adding information about decimal and non decimal currencies
There is lack of information about decimal and non decimal currencies in the documentation. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index ac4f3fe7b46..ac7f5dfd2cc 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -11596,7 +11596,7 @@
"amount": {
"type": "integer",
"format": "int64",
- "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency",
+ "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)",
"example": 6540,
"nullable": true,
"minimum": 0
@@ -11960,7 +11960,7 @@
"amount": {
"type": "integer",
"format": "int64",
- "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency",
+ "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)",
"minimum": 0
},
"currency": {
@@ -12938,7 +12938,7 @@
"amount": {
"type": "integer",
"format": "int64",
- "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency",
+ "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)",
"example": 6540,
"nullable": true,
"minimum": 0
@@ -14048,7 +14048,7 @@
"amount": {
"type": "integer",
"format": "int64",
- "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency",
+ "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)",
"example": 6540,
"nullable": true,
"minimum": 0
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index cd32c045f18..eac7c9888aa 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -278,7 +278,7 @@ pub struct CustomerDetailsResponse {
#[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)]
#[serde(deny_unknown_fields)]
pub struct PaymentsRequest {
- /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency
+ /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)
#[schema(value_type = Option<u64>, example = 6540)]
#[serde(default, deserialize_with = "amount::deserialize_option")]
#[mandatory_in(PaymentsCreateRequest = u64)]
| 2024-09-11T06:20:15Z |
## 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 #5852.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
--> | 034f736ea6e25ae2c75e74dedc12ac54f5979d68 | [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/payments.rs"
] | ||
juspay/hyperswitch | juspay__hyperswitch-5846 | Bug: feat(payments): add support for profile aggregates
Show count of aggregate payments status in the given time range for a particular profile | diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index e5b0e8b9120..62fb06fd522 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -71,6 +71,7 @@ pub trait PaymentIntentInterface {
async fn get_intent_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: &api_models::payments::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f94a5a4633b..4eedb52c99d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3234,11 +3234,12 @@ pub async fn get_payment_filters(
pub async fn get_aggregates_for_payments(
state: SessionState,
merchant: domain::MerchantAccount,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: api::TimeRange,
) -> RouterResponse<api::PaymentsAggregateResponse> {
let db = state.store.as_ref();
let intent_status_with_count = db
- .get_intent_status_with_count(merchant.get_id(), &time_range)
+ .get_intent_status_with_count(merchant.get_id(), profile_id_list, &time_range)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 2088177754e..76111afc6bd 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1640,10 +1640,11 @@ impl PaymentIntentInterface for KafkaStore {
async fn get_intent_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
+ profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: &api_models::payments::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> {
self.diesel_store
- .get_intent_status_with_count(merchant_id, time_range)
+ .get_intent_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 4f8e269dff9..210ded9c25d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -547,6 +547,10 @@ impl Payments {
.service(web::resource("/filter").route(web::post().to(get_filters_for_payments)))
.service(web::resource("/v2/filter").route(web::get().to(get_payment_filters)))
.service(web::resource("/aggregate").route(web::get().to(get_payments_aggregates)))
+ .service(
+ web::resource("/profile/aggregate")
+ .route(web::get().to(get_payments_aggregates_profile)),
+ )
.service(
web::resource("/v2/profile/filter")
.route(web::get().to(get_payment_filters_profile)),
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 18460d6329e..8f3ee3dd4bc 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1341,7 +1341,7 @@ pub async fn get_payments_aggregates(
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
- payments::get_aggregates_for_payments(state, auth.merchant_account, req)
+ payments::get_aggregates_for_payments(state, auth.merchant_account, None, req)
},
&auth::JWTAuth {
permission: Permission::PaymentRead,
@@ -2074,3 +2074,34 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest {
}
}
}
+
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))]
+#[cfg(feature = "olap")]
+pub async fn get_payments_aggregates_profile(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ payload: web::Query<payment_types::TimeRange>,
+) -> impl Responder {
+ let flow = Flow::PaymentsAggregate;
+ let payload = payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, req, _| {
+ payments::get_aggregates_for_payments(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
+ },
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Profile,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index f5db60da3fa..e296c88b3ac 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -44,6 +44,7 @@ impl PaymentIntentInterface for MockDb {
async fn get_intent_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
+ _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_time_range: &api_models::payments::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index f69c26e6409..90395e15dac 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -350,10 +350,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &api_models::payments::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
self.router_store
- .get_intent_status_with_count(merchant_id, time_range)
+ .get_intent_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
@@ -670,6 +671,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &api_models::payments::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await.switch()?;
@@ -681,6 +683,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
+ if let Some(profile_id) = profile_id_list {
+ query = query.filter(pi_dsl::profile_id.eq_any(profile_id));
+ }
+
query = query.filter(pi_dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
| 2024-09-10T07:40:31Z |
## Description
<!-- Describe your changes in detail -->
- Add support for profile level aggregates in payments.
- For now it will have list of intent status along with the their count for a given time range.
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #[#5846](https://github.com/juspay/hyperswitch/issues/5846)
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Request :
```
curl --location 'http://localhost:8080/payments/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT token' \
--data ''
```
Response :
```
{
"status_with_count": {
"failed": 5,
"cancelled": 0,
"processing": 0,
"requires_capture": 0,
"partially_captured_and_capturable": 0,
"requires_merchant_action": 0,
"requires_payment_method": 0,
"requires_customer_action": 0,
"requires_confirmation": 0,
"succeeded": 40,
"partially_captured": 0
}
}
``` | 296ca311c96cc032aaa9ad846299db24bacaeb56 |
Request :
```
curl --location 'http://localhost:8080/payments/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \
--header 'Authorization: Bearer JWT token' \
--data ''
```
Response :
```
{
"status_with_count": {
"failed": 5,
"cancelled": 0,
"processing": 0,
"requires_capture": 0,
"partially_captured_and_capturable": 0,
"requires_merchant_action": 0,
"requires_payment_method": 0,
"requires_customer_action": 0,
"requires_confirmation": 0,
"succeeded": 40,
"partially_captured": 0
}
}
```
| [
"crates/hyperswitch_domain_models/src/payments/payment_intent.rs",
"crates/router/src/core/payments.rs",
"crates/router/src/db/kafka_store.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/payments.rs",
"crates/storage_impl/src/mock_db/payment_intent.rs",
"crates/storage_impl/src/payment... | |
juspay/hyperswitch | juspay__hyperswitch-5842 | Bug: feat(roles): New roles for profile level
Create new roles for profile level roles.
- profile_admin
- profile_view_only
- profile_operator
- profile_developer
- profile_iam | diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 879db9a5a67..1fcfbdb5df9 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -419,7 +419,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -465,7 +465,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -545,7 +545,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -591,7 +591,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -671,7 +671,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -717,7 +717,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -931,7 +931,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -967,7 +967,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1056,7 +1056,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -1092,7 +1092,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1179,7 +1179,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1213,7 +1213,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1245,7 +1245,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1776,7 +1776,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1808,7 +1808,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1851,7 +1851,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1894,7 +1894,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1961,7 +1961,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -1990,7 +1990,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
@@ -2077,7 +2077,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -2116,7 +2116,7 @@ pub mod routes {
},
&auth::JWTAuth {
permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Organization,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs
index fbabec67291..3cc2cb26886 100644
--- a/crates/router/src/consts/user_role.rs
+++ b/crates/router/src/consts/user_role.rs
@@ -5,6 +5,13 @@ pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin";
pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer";
pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator";
pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support";
+
+pub const ROLE_ID_PROFILE_ADMIN: &str = "profile_admin";
+pub const ROLE_ID_PROFILE_VIEW_ONLY: &str = "profile_view_only";
+pub const ROLE_ID_PROFILE_IAM_ADMIN: &str = "profile_iam_admin";
+pub const ROLE_ID_PROFILE_DEVELOPER: &str = "profile_developer";
+pub const ROLE_ID_PROFILE_OPERATOR: &str = "profile_operator";
pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support";
+
pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000";
pub const MAX_ROLE_NAME_LENGTH: usize = 64;
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 8c42e8df353..e423f861078 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2652,6 +2652,7 @@ pub async fn create_connector(
state: SessionState,
req: api::MerchantConnectorCreate,
merchant_account: domain::MerchantAccount,
+ auth_profile_id: Option<id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
@@ -2683,6 +2684,8 @@ pub async fn create_connector(
.validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store)
.await?;
+ core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?;
+
let pm_auth_config_validation = PMAuthConfigValidation {
connector_type: &req.connector_type,
pm_auth_config: &req.pm_auth_config,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index ae92360b13e..0dc34aa4245 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -226,14 +226,20 @@ pub async fn connector_create(
&req,
payload,
|state, auth_data, req, _| {
- create_connector(state, req, auth_data.merchant_account, auth_data.key_store)
+ create_connector(
+ state,
+ req,
+ auth_data.merchant_account,
+ auth_data.profile_id,
+ auth_data.key_store,
+ )
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -259,7 +265,13 @@ pub async fn connector_create(
&req,
payload,
|state, auth_data, req, _| {
- create_connector(state, req, auth_data.merchant_account, auth_data.key_store)
+ create_connector(
+ state,
+ req,
+ auth_data.merchant_account,
+ None,
+ auth_data.key_store,
+ )
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
@@ -526,7 +538,7 @@ pub async fn connector_update(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -889,8 +901,8 @@ pub async fn business_profile_update(
&auth::JWTAuthMerchantAndProfileFromRoute {
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
- minimum_entity_level: EntityType::Merchant,
required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index e4d7337ef72..e2cb50b0aa7 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -666,14 +666,14 @@ pub async fn list_countries_currencies_for_connector_payment_method(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 8533c9ddea9..b1831068991 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -45,14 +45,14 @@ pub async fn routing_create_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -88,14 +88,14 @@ pub async fn routing_link_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -352,14 +352,14 @@ pub async fn routing_unlink_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -478,7 +478,7 @@ pub async fn routing_retrieve_default_config(
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -486,7 +486,7 @@ pub async fn routing_retrieve_default_config(
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -963,7 +963,7 @@ pub async fn routing_update_default_config_for_profile(
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -971,7 +971,7 @@ pub async fn routing_update_default_config_for_profile(
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 34097b6bac6..62af1d4374c 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -177,7 +177,7 @@ pub async fn set_dashboard_metadata(
user_core::dashboard_metadata::set_metadata,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -365,7 +365,7 @@ pub async fn list_user_roles_details(
user_core::list_user_roles_details,
&auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -468,7 +468,7 @@ pub async fn invite_multiple_user(
},
&auth::JWTAuth {
permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -494,7 +494,7 @@ pub async fn resend_invite(
},
&auth::JWTAuth {
permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 00b289b0b80..b1260b5d7ad 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -114,7 +114,7 @@ pub async fn get_role(
},
&auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -160,7 +160,7 @@ pub async fn update_user_role(
user_role_core::update_user_role,
&auth::JWTAuth {
permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -261,7 +261,7 @@ pub async fn delete_user_role(
user_role_core::delete_user_role,
&auth::JWTAuth {
permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -282,9 +282,10 @@ pub async fn get_role_information(
|_, _: (), _, _| async move {
user_role_core::get_authorization_info_with_group_tag().await
},
- &auth::JWTAuth{
+ &auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant},
+ minimum_entity_level: EntityType::Profile
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -318,7 +319,7 @@ pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest)
|state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token),
&auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -347,7 +348,7 @@ pub async fn list_invitable_roles_at_entity_level(
},
&auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -376,7 +377,7 @@ pub async fn list_updatable_roles_at_entity_level(
},
&auth::JWTAuth {
permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 8bac297e7c2..df42d412989 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -8,6 +8,8 @@ use crate::consts;
pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| {
let mut roles = HashMap::new();
+
+ // Internal Roles
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_ADMIN,
RoleInfo {
@@ -58,6 +60,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
},
);
+ // Merchant Roles
roles.insert(
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN,
RoleInfo {
@@ -106,7 +109,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::ReconOps,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
- role_name: "admin".to_string(),
+ role_name: "merchant_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
@@ -127,7 +130,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
- role_name: "view_only".to_string(),
+ role_name: "merchant_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
@@ -147,7 +150,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
- role_name: "iam".to_string(),
+ role_name: "merchant_iam".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
@@ -168,7 +171,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
- role_name: "developer".to_string(),
+ role_name: "merchant_developer".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
@@ -190,7 +193,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
- role_name: "operator".to_string(),
+ role_name: "merchant_operator".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
@@ -218,17 +221,129 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
is_internal: false,
},
);
+
+ // Profile Roles
roles.insert(
- consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT,
+ consts::user_role::ROLE_ID_PROFILE_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
+ PermissionGroup::ConnectorsManage,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::WorkflowsManage,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(),
+ role_name: "profile_admin".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(),
+ role_name: "profile_view_only".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::UsersManage,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(),
+ role_name: "profile_iam".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_DEVELOPER,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ PermissionGroup::MerchantDetailsManage,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(),
+ role_name: "profile_developer".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_OPERATOR,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(),
+ role_name: "profile_operator".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::AnalyticsView,
+ PermissionGroup::UsersView,
+ PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(),
- role_name: "profile_support".to_string(),
+ role_name: "profile_customer_support".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
| 2024-09-09T13:52:12Z |
## Description
<!-- Describe your changes in detail -->
- Make merchant account create profile level.
- Create new roles for profile users.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #5842.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Invite user at any of the following roles:
- profile_admin
- profile_view_only
- profile_iam_admin
- profile_developer
- profile_operator
Dashboard features should work without 401s. | bf1797fe7cf769eb6e89f75b132a35a6cd9003df |
Invite user at any of the following roles:
- profile_admin
- profile_view_only
- profile_iam_admin
- profile_developer
- profile_operator
Dashboard features should work without 401s.
| [
"crates/router/src/analytics.rs",
"crates/router/src/consts/user_role.rs",
"crates/router/src/core/admin.rs",
"crates/router/src/routes/admin.rs",
"crates/router/src/routes/payment_methods.rs",
"crates/router/src/routes/routing.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/routes/user_ro... | |
juspay/hyperswitch | juspay__hyperswitch-5756 | Bug: Interfacing of client and gRPC communications to Dynamo
Building a gRPC Client for communicating with the Dynamo server, once the dynamic routing feature has been enabled.
The dynamic routing feature would be a compile time as well as runtime feature flag ,
for providing the flexibility to enable and disable the dynamic routing during deployment
#### Possible Implementation:
Once dynamic routing has been enabled , we will store the default config in the algorithm column in routing table as the following jsonb:
```
{
"id": "merchant_id",
"params": "card",
"labels": ["stripe","adyen"],
"config": {
"min_aggregates_size": 2,
"default_success_rate": 100.0
}
}
```
gRPC client will be integrated as a dynamic dispatch field of the DynamicRouting trait within the struct SessionState,
which would be under the dynamic_routing feature flag
```
struct SessionState
{
pub grpc: Box<dyn DynamicRouting>
}
```
The DynamicRouting trait would have following functions:
calculate_the_success_rate
update_the_success_rates
```
triat DynamicRouting
{
async fn calculate_success_rate(self,label_input : Vec<T>) -> CalSuccessRateResponse
async fn update_success_rate(self,calculated_success_rate:CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
}
```
The trait DynamicRouting would be implemented on the the struct SuccessRateCalculator taken from the .proto file
```
impl DynamicRouting for SuccessRateCalculator
{
async fn calculate_success_rate(self,label_input : T) -> CalSuccessRateResponse
{
self.fetch_success_rate(request)
}
async fn update_success_rate(self,calculated_success_rate : CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
{
self.update_success_rate_window(request)
}
}
```
| diff --git a/Cargo.lock b/Cargo.lock
index 11036b42dc4..d90c577152d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1433,7 +1433,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
- "axum-core",
+ "axum-core 0.3.4",
"bitflags 1.3.2",
"bytes 1.7.1",
"futures-util",
@@ -1454,6 +1454,33 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "axum"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a6c9af12842a67734c9a2e355436e5d03b22383ed60cf13cd0c18fbfe3dcbcf"
+dependencies = [
+ "async-trait",
+ "axum-core 0.4.3",
+ "bytes 1.7.1",
+ "futures-util",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "rustversion",
+ "serde",
+ "sync_wrapper 1.0.1",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "axum-core"
version = "0.3.4"
@@ -1471,6 +1498,26 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "axum-core"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a15c63fd72d41492dc4f497196f5da1fb04fb7529e631d73630d1b491e47a2e3"
+dependencies = [
+ "async-trait",
+ "bytes 1.7.1",
+ "futures-util",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "rustversion",
+ "sync_wrapper 0.1.2",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "backtrace"
version = "0.3.73"
@@ -3064,6 +3111,7 @@ dependencies = [
name = "external_services"
version = "0.1.0"
dependencies = [
+ "api_models",
"async-trait",
"aws-config 0.55.3",
"aws-sdk-kms",
@@ -3081,10 +3129,15 @@ dependencies = [
"hyperswitch_interfaces",
"masking",
"once_cell",
+ "prost 0.13.2",
"router_env",
"serde",
"thiserror",
"tokio 1.40.0",
+ "tonic 0.12.2",
+ "tonic-build",
+ "tonic-reflection",
+ "tonic-types",
"vaultrs",
]
@@ -3160,6 +3213,12 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+[[package]]
+name = "fixedbitset"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
+
[[package]]
name = "flate2"
version = "1.0.33"
@@ -3854,6 +3913,19 @@ dependencies = [
"tokio-io-timeout",
]
+[[package]]
+name = "hyper-timeout"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3203a961e5c83b6f5498933e78b6b263e208c197b63e9c6c53cc82ffd3f63793"
+dependencies = [
+ "hyper 1.4.1",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio 1.40.0",
+ "tower-service",
+]
+
[[package]]
name = "hyper-tls"
version = "0.5.0"
@@ -4727,6 +4799,12 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "multimap"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03"
+
[[package]]
name = "mutually_exclusive_features"
version = "0.0.3"
@@ -5114,10 +5192,10 @@ dependencies = [
"http 0.2.12",
"opentelemetry",
"opentelemetry-proto",
- "prost",
+ "prost 0.11.9",
"thiserror",
"tokio 1.40.0",
- "tonic",
+ "tonic 0.8.3",
]
[[package]]
@@ -5129,8 +5207,8 @@ dependencies = [
"futures 0.3.30",
"futures-util",
"opentelemetry",
- "prost",
- "tonic",
+ "prost 0.11.9",
+ "tonic 0.8.3",
]
[[package]]
@@ -5389,6 +5467,16 @@ dependencies = [
"sha2",
]
+[[package]]
+name = "petgraph"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
+dependencies = [
+ "fixedbitset",
+ "indexmap 2.5.0",
+]
+
[[package]]
name = "phf"
version = "0.11.2"
@@ -5591,6 +5679,16 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.77",
+]
+
[[package]]
name = "primeorder"
version = "0.13.6"
@@ -5679,7 +5777,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd"
dependencies = [
"bytes 1.7.1",
- "prost-derive",
+ "prost-derive 0.11.9",
+]
+
+[[package]]
+name = "prost"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b2ecbe40f08db5c006b5764a2645f7f3f141ce756412ac9e1dd6087e6d32995"
+dependencies = [
+ "bytes 1.7.1",
+ "prost-derive 0.13.2",
+]
+
+[[package]]
+name = "prost-build"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302"
+dependencies = [
+ "bytes 1.7.1",
+ "heck 0.5.0",
+ "itertools 0.12.1",
+ "log",
+ "multimap",
+ "once_cell",
+ "petgraph",
+ "prettyplease",
+ "prost 0.13.2",
+ "prost-types",
+ "regex",
+ "syn 2.0.77",
+ "tempfile",
]
[[package]]
@@ -5695,6 +5824,28 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "prost-derive"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac"
+dependencies = [
+ "anyhow",
+ "itertools 0.12.1",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.77",
+]
+
+[[package]]
+name = "prost-types"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60caa6738c7369b940c3d49246a8d1749323674c65cb13010134f5c9bad5b519"
+dependencies = [
+ "prost 0.13.2",
+]
+
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -8215,7 +8366,7 @@ checksum = "8f219fad3b929bef19b1f86fbc0358d35daed8f2cac972037ac0dc10bbb8d5fb"
dependencies = [
"async-stream",
"async-trait",
- "axum",
+ "axum 0.6.20",
"base64 0.13.1",
"bytes 1.7.1",
"futures-core",
@@ -8224,11 +8375,11 @@ dependencies = [
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.30",
- "hyper-timeout",
+ "hyper-timeout 0.4.1",
"percent-encoding",
"pin-project",
- "prost",
- "prost-derive",
+ "prost 0.11.9",
+ "prost-derive 0.11.9",
"tokio 1.40.0",
"tokio-stream",
"tokio-util",
@@ -8239,6 +8390,73 @@ dependencies = [
"tracing-futures",
]
+[[package]]
+name = "tonic"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f6ba989e4b2c58ae83d862d3a3e27690b6e3ae630d0deb59f3697f32aa88ad"
+dependencies = [
+ "async-stream",
+ "async-trait",
+ "axum 0.7.5",
+ "base64 0.22.1",
+ "bytes 1.7.1",
+ "h2 0.4.6",
+ "http 1.1.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "hyper 1.4.1",
+ "hyper-timeout 0.5.1",
+ "hyper-util",
+ "percent-encoding",
+ "pin-project",
+ "prost 0.13.2",
+ "socket2",
+ "tokio 1.40.0",
+ "tokio-stream",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tonic-build"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe4ee8877250136bd7e3d2331632810a4df4ea5e004656990d8d66d2f5ee8a67"
+dependencies = [
+ "prettyplease",
+ "proc-macro2",
+ "prost-build",
+ "quote",
+ "syn 2.0.77",
+]
+
+[[package]]
+name = "tonic-reflection"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b56b874eedb04f89907573b408eab1e87c1c1dce43aac6ad63742f57faa99ff"
+dependencies = [
+ "prost 0.13.2",
+ "prost-types",
+ "tokio 1.40.0",
+ "tokio-stream",
+ "tonic 0.12.2",
+]
+
+[[package]]
+name = "tonic-types"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d967793411bc1a5392accf4731114295f0fd122865d22cde46a8584b03402b2"
+dependencies = [
+ "prost 0.13.2",
+ "prost-types",
+ "tonic 0.12.2",
+]
+
[[package]]
name = "totp-rs"
version = "5.6.0"
diff --git a/Dockerfile b/Dockerfile
index 29c1003c115..65ca6370364 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,7 +4,7 @@ ARG EXTRA_FEATURES=""
ARG VERSION_FEATURE_SET="v1"
RUN apt-get update \
- && apt-get install -y libpq-dev libssl-dev pkg-config
+ && apt-get install -y libpq-dev libssl-dev pkg-config protobuf-compiler
# Copying codebase from current dir to /router dir
# and creating a fresh build
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 5023d30f722..2b551eaebb7 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -197,7 +197,9 @@ pub enum RoutableChoiceSerde {
impl std::fmt::Display for RoutableConnectorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = self.connector.to_string();
-
+ if let Some(mca_id) = &self.merchant_connector_id {
+ return write!(f, "{}:{}", base, mca_id.get_string_repr());
+ }
write!(f, "{}", base)
}
}
@@ -252,6 +254,11 @@ impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
}
}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+pub struct RoutableConnectorChoiceWithStatus {
+ pub routable_connector_choice: RoutableConnectorChoice,
+ pub status: bool,
+}
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
@@ -565,7 +572,7 @@ impl Default for SuccessBasedRoutingConfig {
}
}
-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)]
pub enum SuccessBasedRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 9051c58ea59..a882cdc9f51 100644
--- a/crates/external_services/Cargo.toml
+++ b/crates/external_services/Cargo.toml
@@ -13,6 +13,7 @@ email = ["dep:aws-config"]
aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"]
hashicorp-vault = ["dep:vaultrs"]
v1 = ["hyperswitch_interfaces/v1"]
+dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread"]
[dependencies]
async-trait = "0.1.79"
@@ -31,14 +32,24 @@ hyper-proxy = "0.9.1"
once_cell = "1.19.0"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
-tokio = "1.37.0"
vaultrs = { version = "0.7.2", optional = true }
+prost = { version = "0.13", optional = true }
+tokio = "1.37.0"
+tonic = { version = "0.12.2", optional = true }
+tonic-reflection = { version = "0.12.2", optional = true }
+tonic-types = { version = "0.12.2", optional = true }
+
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+api_models = { version = "0.1.0", path = "../api_models", optional = true }
+
+
+[build-dependencies]
+tonic-build = "0.12"
[lints]
workspace = true
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
new file mode 100644
index 00000000000..61e19f308d8
--- /dev/null
+++ b/crates/external_services/build.rs
@@ -0,0 +1,15 @@
+use std::{env, path::PathBuf};
+
+#[allow(clippy::expect_used)]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ // Get the directory of the current crate
+ let crate_dir = env::var("CARGO_MANIFEST_DIR")?;
+ let proto_file = PathBuf::from(crate_dir)
+ .join("..")
+ .join("..")
+ .join("proto")
+ .join("success_rate.proto");
+ // Compile the .proto file
+ tonic_build::compile_protos(proto_file).expect("Failed to compile protos ");
+ Ok(())
+}
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
new file mode 100644
index 00000000000..5afd3024551
--- /dev/null
+++ b/crates/external_services/src/grpc_client.rs
@@ -0,0 +1,48 @@
+/// Dyanimc Routing Client interface implementation
+#[cfg(feature = "dynamic_routing")]
+pub mod dynamic_routing;
+use std::{fmt::Debug, sync::Arc};
+
+#[cfg(feature = "dynamic_routing")]
+use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy};
+use router_env::logger;
+use serde;
+
+/// Struct contains all the gRPC Clients
+#[derive(Debug, Clone)]
+pub struct GrpcClients {
+ /// The routing client
+ #[cfg(feature = "dynamic_routing")]
+ pub dynamic_routing: RoutingStrategy,
+}
+/// Type that contains the configs required to construct a gRPC client with its respective services.
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
+pub struct GrpcClientSettings {
+ #[cfg(feature = "dynamic_routing")]
+ /// Configs for Dynamic Routing Client
+ pub dynamic_routing_client: DynamicRoutingClientConfig,
+}
+
+impl GrpcClientSettings {
+ /// # Panics
+ ///
+ /// This function will panic if it fails to establish a connection with the gRPC server.
+ /// This function will be called at service startup.
+ #[allow(clippy::expect_used)]
+ pub async fn get_grpc_client_interface(&self) -> Arc<GrpcClients> {
+ #[cfg(feature = "dynamic_routing")]
+ let dynamic_routing_connection = self
+ .dynamic_routing_client
+ .clone()
+ .get_dynamic_routing_connection()
+ .await
+ .expect("Failed to establish a connection with the Dynamic Routing Server");
+
+ logger::info!("Connection established with gRPC Server");
+
+ Arc::new(GrpcClients {
+ #[cfg(feature = "dynamic_routing")]
+ dynamic_routing: dynamic_routing_connection,
+ })
+ }
+}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
new file mode 100644
index 00000000000..17bd43ca3a8
--- /dev/null
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -0,0 +1,265 @@
+use std::fmt::Debug;
+
+use api_models::routing::{
+ CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,
+};
+use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom};
+use error_stack::ResultExt;
+use serde;
+use success_rate::{
+ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
+ CalSuccessRateRequest, CalSuccessRateResponse,
+ CurrentBlockThreshold as DynamicCurrentThreshold, LabelWithStatus,
+ UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
+};
+use tonic::transport::Channel;
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions
+)]
+pub mod success_rate {
+ tonic::include_proto!("success_rate");
+}
+/// Result type for Dynamic Routing
+pub type DynamicRoutingResult<T> = CustomResult<T, DynamicRoutingError>;
+
+/// Dynamic Routing Errors
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum DynamicRoutingError {
+ /// The required input is missing
+ #[error("Missing Required Field : {field} for building the Dynamic Routing Request")]
+ MissingRequiredField {
+ /// The required field name
+ field: String,
+ },
+ /// Error from Dynamic Routing Server
+ #[error("Error from Dynamic Routing Server : {0}")]
+ SuccessRateBasedRoutingFailure(String),
+}
+
+/// Type that consists of all the services provided by the client
+#[derive(Debug, Clone)]
+pub struct RoutingStrategy {
+ /// success rate service for Dynamic Routing
+ pub success_rate_client: Option<SuccessRateCalculatorClient<Channel>>,
+}
+
+/// Contains the Dynamic Routing Client Config
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
+#[serde(untagged)]
+pub enum DynamicRoutingClientConfig {
+ /// If the dynamic routing client config has been enabled
+ Enabled {
+ /// The host for the client
+ host: String,
+ /// The port of the client
+ port: u16,
+ },
+ #[default]
+ /// If the dynamic routing client config has been disabled
+ Disabled,
+}
+
+impl DynamicRoutingClientConfig {
+ /// establish connection with the server
+ pub async fn get_dynamic_routing_connection(
+ self,
+ ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
+ let success_rate_client = match self {
+ Self::Enabled { host, port } => {
+ let uri = format!("http://{}:{}", host, port);
+ let channel = tonic::transport::Endpoint::new(uri)?.connect().await?;
+ Some(SuccessRateCalculatorClient::new(channel))
+ }
+ Self::Disabled => None,
+ };
+ Ok(RoutingStrategy {
+ success_rate_client,
+ })
+ }
+}
+
+/// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window
+#[async_trait::async_trait]
+pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
+ /// To calculate the success rate for the list of chosen connectors
+ async fn calculate_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoice>,
+ ) -> DynamicRoutingResult<CalSuccessRateResponse>;
+ /// To update the success rate with the given label
+ async fn update_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ response: Vec<RoutableConnectorChoiceWithStatus>,
+ ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
+}
+
+#[async_trait::async_trait]
+impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
+ async fn calculate_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoice>,
+ ) -> DynamicRoutingResult<CalSuccessRateResponse> {
+ let params = success_rate_based_config
+ .params
+ .map(|vec| {
+ vec.into_iter().fold(String::new(), |mut acc_vec, params| {
+ if !acc_vec.is_empty() {
+ acc_vec.push(':')
+ }
+ acc_vec.push_str(params.to_string().as_str());
+ acc_vec
+ })
+ })
+ .get_required_value("params")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "params".to_string(),
+ })?;
+
+ let labels = label_input
+ .into_iter()
+ .map(|conn_choice| conn_choice.to_string())
+ .collect::<Vec<_>>();
+
+ let config = success_rate_based_config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let request = tonic::Request::new(CalSuccessRateRequest {
+ id,
+ params,
+ labels,
+ config,
+ });
+
+ let mut client = self.clone();
+
+ let response = client
+ .fetch_success_rate(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to fetch the success rate".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+
+ async fn update_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ label_input: Vec<RoutableConnectorChoiceWithStatus>,
+ ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
+ let config = success_rate_based_config
+ .config
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?;
+
+ let labels_with_status = label_input
+ .into_iter()
+ .map(|conn_choice| LabelWithStatus {
+ label: conn_choice.routable_connector_choice.to_string(),
+ status: conn_choice.status,
+ })
+ .collect();
+
+ let params = success_rate_based_config
+ .params
+ .map(|vec| {
+ vec.into_iter().fold(String::new(), |mut acc_vec, params| {
+ if !acc_vec.is_empty() {
+ acc_vec.push(':')
+ }
+ acc_vec.push_str(params.to_string().as_str());
+ acc_vec
+ })
+ })
+ .get_required_value("params")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "params".to_string(),
+ })?;
+
+ let request = tonic::Request::new(UpdateSuccessRateWindowRequest {
+ id,
+ params,
+ labels_with_status,
+ config,
+ });
+
+ let mut client = self.clone();
+
+ let response = client
+ .update_success_rate_window(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to update the success rate window".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+}
+
+impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(current_threshold: CurrentBlockThreshold) -> Result<Self, Self::Error> {
+ Ok(Self {
+ duration_in_mins: current_threshold.duration_in_mins,
+ max_total_count: current_threshold
+ .max_total_count
+ .get_required_value("max_total_count")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "max_total_count".to_string(),
+ })?,
+ })
+ }
+}
+
+impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for UpdateSuccessRateWindowConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ max_aggregates_size: config
+ .max_aggregates_size
+ .get_required_value("max_aggregate_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "max_aggregates_size".to_string(),
+ })?,
+ current_block_threshold: config
+ .current_block_threshold
+ .map(ForeignTryFrom::foreign_try_from)
+ .transpose()?,
+ })
+ }
+}
+
+impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
+ Ok(Self {
+ min_aggregates_size: config
+ .min_aggregates_size
+ .get_required_value("min_aggregate_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "min_aggregates_size".to_string(),
+ })?,
+ default_success_rate: config
+ .default_success_rate
+ .get_required_value("default_success_rate")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "default_success_rate".to_string(),
+ })?,
+ })
+ }
+}
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index f4bcd91e343..4570a5e5960 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -14,6 +14,9 @@ pub mod hashicorp_vault;
pub mod no_encryption;
+/// Building grpc clients to communicate with the server
+pub mod grpc_client;
+
pub mod managers;
/// Crate specific constants
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 0b4545a33d7..7205865f24a 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -16,7 +16,6 @@ pub mod payouts;
pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
-
use common_enums::enums::{CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType};
use common_utils::{
errors::CustomResult,
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index bae6243d2e6..442561c2ca3 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -38,6 +38,7 @@ v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
+dynamic_routing = ["external_services/dynamic_routing"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 9b0bfbb40b2..604dce5047c 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -497,6 +497,7 @@ pub(crate) async fn fetch_raw_secrets(
user_auth_methods,
decision: conf.decision,
locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors,
+ grpc_client: conf.grpc_client,
recipient_emails: conf.recipient_emails,
network_tokenization_supported_card_networks: conf
.network_tokenization_supported_card_networks,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 78ff709cc02..7d6dfd26eae 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -13,6 +13,7 @@ use error_stack::ResultExt;
use external_services::email::EmailSettings;
use external_services::{
file_storage::FileStorageConfig,
+ grpc_client::GrpcClientSettings,
managers::{
encryption_management::EncryptionManagementConfig,
secrets_management::SecretsManagementConfig,
@@ -120,6 +121,7 @@ pub struct Settings<S: SecretState> {
pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>,
pub decision: Option<DecisionConfig>,
pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList,
+ pub grpc_client: GrpcClientSettings,
pub recipient_emails: RecipientMails,
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0af5bf6037a..30d619efedc 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -11,7 +11,6 @@ pub mod routing;
pub mod tokenization;
pub mod transformers;
pub mod types;
-
#[cfg(feature = "olap")]
use std::collections::HashMap;
use std::{
@@ -160,7 +159,6 @@ where
&header_payload,
)
.await?;
-
utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
@@ -4427,6 +4425,7 @@ where
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index a68f648e178..8ba214f94b9 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -361,7 +361,7 @@ pub async fn connector_retrieve(
})
.into_inner();
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -384,7 +384,7 @@ pub async fn connector_retrieve(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
/// Merchant Connector - Retrieve
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 71632cc5749..a00e740b3e6 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -166,7 +166,7 @@ pub async fn api_key_update(
payload.key_id = key_id;
payload.merchant_id.clone_from(&merchant_id);
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -182,7 +182,7 @@ pub async fn api_key_update(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index aad5acbbade..034b3784f40 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -9,7 +9,7 @@ use common_enums::TransactionType;
use common_utils::crypto::Blake3;
#[cfg(feature = "email")]
use external_services::email::{ses::AwsSes, EmailService};
-use external_services::file_storage::FileStorageInterface;
+use external_services::{file_storage::FileStorageInterface, grpc_client::GrpcClients};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{RawSecret, SecuredSecret},
@@ -105,6 +105,7 @@ pub struct SessionState {
pub tenant: Tenant,
#[cfg(feature = "olap")]
pub opensearch_client: Arc<OpenSearchClient>,
+ pub grpc_client: Arc<GrpcClients>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
@@ -202,6 +203,7 @@ pub struct AppState {
pub request_id: Option<RequestId>,
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
+ pub grpc_client: Arc<GrpcClients>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<String> {
@@ -351,6 +353,8 @@ impl AppState {
let file_storage_client = conf.file_storage.get_file_storage_client().await;
+ let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
+
Self {
flow_name: String::from("default"),
stores,
@@ -367,6 +371,7 @@ impl AppState {
request_id: None,
file_storage_client,
encryption_client,
+ grpc_client,
}
})
.await
@@ -447,6 +452,7 @@ impl AppState {
email_client: Arc::clone(&self.email_client),
#[cfg(feature = "olap")]
opensearch_client: Arc::clone(&self.opensearch_client),
+ grpc_client: Arc::clone(&self.grpc_client),
})
}
}
diff --git a/crates/router/src/routes/dummy_connector.rs b/crates/router/src/routes/dummy_connector.rs
index 26c32776d72..e376bcd7f9e 100644
--- a/crates/router/src/routes/dummy_connector.rs
+++ b/crates/router/src/routes/dummy_connector.rs
@@ -46,7 +46,7 @@ pub async fn dummy_connector_complete_payment(
attempt_id,
confirm: json_payload.confirm,
};
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -54,7 +54,7 @@ pub async fn dummy_connector_complete_payment(
|state, _: (), req, _| core::payment_complete(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentCreate))]
@@ -65,7 +65,7 @@ pub async fn dummy_connector_payment(
) -> impl actix_web::Responder {
let payload = json_payload.into_inner();
let flow = types::Flow::DummyPaymentCreate;
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -73,7 +73,7 @@ pub async fn dummy_connector_payment(
|state, _: (), req, _| core::payment(state, req),
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
#[instrument(skip_all, fields(flow = ?types::Flow::DummyPaymentRetrieve))]
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 86ad2078f6c..70da80c6756 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -612,7 +612,7 @@ pub async fn retrieve_surcharge_decision_manager_config(
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
- oss_api::server_wrap(
+ Box::pin(oss_api::server_wrap(
flow,
state,
&req,
@@ -638,7 +638,7 @@ pub async fn retrieve_surcharge_decision_manager_config(
minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
@@ -727,7 +727,7 @@ pub async fn retrieve_decision_manager_config(
req: HttpRequest,
) -> impl Responder {
let flow = Flow::DecisionManagerRetrieveConfig;
- oss_api::server_wrap(
+ Box::pin(oss_api::server_wrap(
flow,
state,
&req,
@@ -750,7 +750,7 @@ pub async fn retrieve_decision_manager_config(
minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
diff --git a/docker-compose-development.yml b/docker-compose-development.yml
index ebccb114048..cf12982a9bd 100644
--- a/docker-compose-development.yml
+++ b/docker-compose-development.yml
@@ -60,7 +60,9 @@ services:
### Application services
hyperswitch-server:
image: rust:latest
- command: cargo run --bin router -- -f ./config/docker_compose.toml
+ command: |
+ apt-get install -y protobuf-compiler && \
+ cargo run --bin router -- -f ./config/docker_compose.toml
working_dir: /app
ports:
- "8080:8080"
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
index 2482fc9f591..c7a53898129 100644
--- a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
@@ -1,3 +1,5 @@
-- Your SQL goes here
-ALTER TABLE business_profile
-ADD COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
+ALTER TABLE
+ business_profile
+ADD
+ COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
\ No newline at end of file
diff --git a/proto/success_rate.proto b/proto/success_rate.proto
new file mode 100644
index 00000000000..8018f6d5fe4
--- /dev/null
+++ b/proto/success_rate.proto
@@ -0,0 +1,57 @@
+syntax = "proto3";
+package success_rate;
+
+ service SuccessRateCalculator {
+ rpc FetchSuccessRate (CalSuccessRateRequest) returns (CalSuccessRateResponse);
+
+ rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse);
+ }
+
+ // API-1 types
+ message CalSuccessRateRequest {
+ string id = 1;
+ string params = 2;
+ repeated string labels = 3;
+ CalSuccessRateConfig config = 4;
+ }
+
+ message CalSuccessRateConfig {
+ uint32 min_aggregates_size = 1;
+ double default_success_rate = 2;
+ }
+
+ message CalSuccessRateResponse {
+ repeated LabelWithScore labels_with_score = 1;
+ }
+
+ message LabelWithScore {
+ double score = 1;
+ string label = 2;
+ }
+
+ // API-2 types
+ message UpdateSuccessRateWindowRequest {
+ string id = 1;
+ string params = 2;
+ repeated LabelWithStatus labels_with_status = 3;
+ UpdateSuccessRateWindowConfig config = 4;
+ }
+
+ message LabelWithStatus {
+ string label = 1;
+ bool status = 2;
+ }
+
+ message UpdateSuccessRateWindowConfig {
+ uint32 max_aggregates_size = 1;
+ CurrentBlockThreshold current_block_threshold = 2;
+ }
+
+ message CurrentBlockThreshold {
+ optional uint64 duration_in_mins = 1;
+ uint64 max_total_count = 2;
+ }
+
+ message UpdateSuccessRateWindowResponse {
+ string message = 1;
+ }
\ No newline at end of file
| 2024-09-09T05:27:48Z |
## Description
Feature Description:
Building a Grpc Client for communicating with the Dynamo server, once the dynamic routing feature has been enabled.
The dynamic routing feature would be a compile time as well as runtime feature flag ,
for providing the flexibility to enable and disable the dynamic routing during deployment
Possible Implementation:
Once dynamic routing has been enabled , we will store the default config in the algorithm column in routing table as the following jsonb:
```
{
"id": "merchant_id",
"params": "card",
"labels": ["stripe","adyen"],
"config": {
"min_aggregates_size": 2,
"default_success_rate": 100.0
}
}
```
gRPC client will be integrated as a struct of GrpcClientInterface within the struct SessionState,
```
struct SessionState
{
grpc: GrpcClientInterface
}
```
The gRPcClientInterface would be a struct which would have Dynamic Routing as its field and similarly any other future gRPC Client would be one of its fields
```
struct gRPcClientInterface
{
pub dynamic_routing: DynamicRouting
}
```
The DynamicRouting struct would have all the fields that would be there as its services channel
```
struct DynamicRouting
{
pub success_based_client : SuccessBasedClient<Channel>
}
```
The SuccessBasedClient would be a trait would have following functions:
calculate_the_success_rate
update_the_success_rates
```
triat SuccessBasedClient
{
type CalCulatedRespons;
type UpadationResponse;
async fn calculate_success_rate(self,label_input : Vec<T>) -> CalCulatedRespons
async fn update_success_rate(self,calculated_success_rate:CalCulatedRespons) -> UpadationResponse
}
```
The SuccessBasedClient would be implemented on client that would be a SuccessBasedClient<Channel>
```
impl SuccessBasedClient for SuccessBasedClient<Channel>
{
async fn calculate_success_rate(self,label_input : T) -> CalSuccessRateResponse
{
self.fetch_success_rate(request)
}
async fn update_success_rate(self,calculated_success_rate : CalSuccessRateResponse) -> UpdateSuccessRateWindowResponse
{
self.update_success_rate_window(request)
}
}
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
- This cannot be tested on sbx, yet
I have tested it locally
- Started the gRPC Server
- Established the connection with the Client <-> Server
- Sent Request the gRPC Server
<img width="1711" alt="Screenshot 2024-09-17 at 7 29 17 PM" src="https://github.com/user-attachments/assets/60fb8ccf-2c4d-48d5-bcfe-f7f3018a915c">
- Response from the server
<img width="1296" alt="Screenshot 2024-09-17 at 7 30 27 PM" src="https://github.com/user-attachments/assets/5de3594b-4701-42a2-9840-a2c14a7db104"> | be902ffa5328d32efe70c40c36f86d8fbfa01c79 | - This cannot be tested on sbx, yet
I have tested it locally
- Started the gRPC Server
- Established the connection with the Client <-> Server
- Sent Request the gRPC Server
<img width="1711" alt="Screenshot 2024-09-17 at 7 29 17 PM" src="https://github.com/user-attachments/assets/60fb8ccf-2c4d-48d5-bcfe-f7f3018a915c">
- Response from the server
<img width="1296" alt="Screenshot 2024-09-17 at 7 30 27 PM" src="https://github.com/user-attachments/assets/5de3594b-4701-42a2-9840-a2c14a7db104">
| [
"Cargo.lock",
"Dockerfile",
"crates/api_models/src/routing.rs",
"crates/external_services/Cargo.toml",
"crates/external_services/build.rs",
"crates/external_services/src/grpc_client.rs",
"crates/external_services/src/grpc_client/dynamic_routing.rs",
"crates/external_services/src/lib.rs",
"crates/hyp... | |
juspay/hyperswitch | juspay__hyperswitch-5831 | Bug: chore: address Rust 1.81.0 clippy lints
Address the clippy lints occurring due to new rust version 1.81.0
See https://github.com/juspay/hyperswitch/issues/3391 for more information. | diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs
index 10514108991..946489513b4 100644
--- a/crates/drainer/src/health_check.rs
+++ b/crates/drainer/src/health_check.rs
@@ -170,7 +170,7 @@ impl HealthCheckInterface for Store {
logger::debug!("Redis set_key was successful");
redis_conn
- .get_key("test_key")
+ .get_key::<()>("test_key")
.await
.change_context(HealthCheckRedisError::GetFailed)?;
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs
index 7d5553bb25c..2707ef4b6f2 100644
--- a/crates/router/src/connector/globalpay.rs
+++ b/crates/router/src/connector/globalpay.rs
@@ -1017,11 +1017,12 @@ impl api::IncomingWebhook for Globalpay {
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
- let details = std::str::from_utf8(request.body)
- .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
- Ok(Box::new(serde_json::from_str(details).change_context(
- errors::ConnectorError::WebhookResourceObjectNotFound,
- )?))
+ Ok(Box::new(
+ request
+ .body
+ .parse_struct::<GlobalpayPaymentsResponse>("GlobalpayPaymentsResponse")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?,
+ ))
}
}
diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs
index 6092ac8bbb9..83faee677d4 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -52,7 +52,7 @@ impl HealthCheckInterface for app::SessionState {
logger::debug!("Redis set_key was successful");
redis_conn
- .get_key("test_key")
+ .get_key::<()>("test_key")
.await
.change_context(errors::HealthCheckRedisError::GetFailed)?;
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 477f025c785..4ea4b60d67d 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -88,11 +88,10 @@ impl SurchargeSource {
)
})
.transpose()?
- .map(|surcharge_details| {
+ .inspect(|surcharge_details| {
let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key;
surcharge_metadata
.insert_surcharge_details(surcharge_key, surcharge_details.clone());
- surcharge_details
}))
}
Self::Predetermined(request_surcharge_details) => Ok(Some(
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f71bf9b94ab..6b231717563 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -145,7 +145,7 @@ where
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
- tracing::Span::current().record("payment_id", &format!("{}", validate_result.payment_id));
+ tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
let operations::GetTrackerResponse {
operation,
diff --git a/crates/router_env/tests/env.rs b/crates/router_env/tests/env.rs
index e4609a48838..cff2ae45f12 100644
--- a/crates/router_env/tests/env.rs
+++ b/crates/router_env/tests/env.rs
@@ -25,7 +25,7 @@ async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg(feature = "vergen")]
#[tokio::test]
-async fn env_macro() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+async fn env_macro() {
println!("version : {:?}", env::version!());
println!("build : {:?}", env::build!());
println!("commit : {:?}", env::commit!());
@@ -35,6 +35,4 @@ async fn env_macro() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
assert!(!env::build!().is_empty());
assert!(!env::commit!().is_empty());
// assert!(env::platform!().len() > 0);
-
- Ok(())
}
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 8511702baa2..74b1526fe8e 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -259,12 +259,11 @@ where
result
.await
- .map(|result| {
+ .inspect(|_| {
logger::debug!(kv_operation= %operation, status="success");
let keyvalue = router_env::opentelemetry::KeyValue::new("operation", operation.clone());
metrics::KV_OPERATION_SUCCESSFUL.add(&metrics::CONTEXT, 1, &[keyvalue]);
- result
})
.inspect_err(|err| {
logger::error!(kv_operation = %operation, status="error", error = ?err);
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 8f24b62fcaf..7d7557a7f5f 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -30,7 +30,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
self.subscriber.manage_subscriptions();
self.subscriber
- .subscribe(channel)
+ .subscribe::<(), &str>(channel)
.await
.change_context(redis_errors::RedisError::SubscribeError)?;
| 2024-09-07T05:19:45Z |
## Description
<!-- Describe your changes in detail -->
This PR addresses the clippy lints occurring due to new rust version 1.81.0
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
This PR addresses clippy lint due to new rust version. So basic sanity testing should suffice. | d9485a5f360f78f308f4e70c361f33873c63b686 |
This PR addresses clippy lint due to new rust version. So basic sanity testing should suffice.
| [
"crates/drainer/src/health_check.rs",
"crates/router/src/connector/globalpay.rs",
"crates/router/src/core/health_check.rs",
"crates/router/src/core/payment_methods/surcharge_decision_configs.rs",
"crates/router/src/core/payments.rs",
"crates/router_env/tests/env.rs",
"crates/storage_impl/src/redis/kv_st... | |
juspay/hyperswitch | juspay__hyperswitch-5755 | Bug: Creation of Toggle and Configs for DynamicRouting & DynamicRoutingMetrics
### Toggle for Dynamic Routing:
There should be a 2 way toggle of the switch:
1. For Success-Based routing(whole integration in core that will affect payments).
2. For only enabling metrics of Success-Based routing (This can be used in future to show users the metrics first and then accordingly the core integration can be enabled).
-> Route 1: Something like GET `/routing/dynamic_routing/enable` or `/routing/dynamic_routing_metrics/enable`.
-> Once Toggled a default config should be created and stored in Routing table to be sent to Dynamo.
-> Add a Boolean value in BusinessProfile table `is_dynamic_routing_enabled`.
-> The code should be under feature flag.
-> Route 2: Update Route (UPDATE `/routing/dynamic_routing/config`) to update the config for users with AdminApiKey auth. | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 3c2c811766b..8e6e58865fc 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -17247,7 +17247,8 @@
"single",
"priority",
"volume_split",
- "advanced"
+ "advanced",
+ "dynamic"
]
},
"RoutingConfigRequest": {
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 2b185d202e1..be3e26b2639 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -2356,6 +2356,10 @@ pub struct BusinessProfileUpdate {
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
+
+ /// Indicates if dynamic routing is enabled or not.
+ #[serde(default)]
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v2")]
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 9cfcafc8733..ffa5e008f0a 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -4,7 +4,9 @@ use crate::routing::{
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
- RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery,
+ RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, SuccessBasedRoutingConfig,
+ SuccessBasedRoutingPayloadWrapper, SuccessBasedRoutingUpdateConfigQuery,
+ ToggleSuccessBasedRoutingQuery, ToggleSuccessBasedRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
@@ -76,3 +78,33 @@ impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper {
Some(ApiEventsType::Routing)
}
}
+
+impl ApiEventMetric for ToggleSuccessBasedRoutingQuery {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingConfig {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for ToggleSuccessBasedRoutingWrapper {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
+
+impl ApiEventMetric for SuccessBasedRoutingUpdateConfigQuery {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Routing)
+ }
+}
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index bec917b06c8..5023d30f722 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -260,6 +260,7 @@ pub enum RoutingAlgorithmKind {
Priority,
VolumeSplit,
Advanced,
+ Dynamic,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -495,3 +496,138 @@ pub struct RoutingLinkWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: RoutingAlgorithmId,
}
+
+#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
+pub struct DynamicAlgorithmWithTimestamp<T> {
+ pub algorithm_id: Option<T>,
+ pub timestamp: i64,
+}
+
+#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
+pub struct DynamicRoutingAlgorithmRef {
+ pub success_based_algorithm:
+ Option<DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>>,
+}
+
+impl DynamicRoutingAlgorithmRef {
+ pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
+ self.success_based_algorithm = Some(DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(new_id),
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ })
+ }
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ToggleSuccessBasedRoutingQuery {
+ pub status: bool,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct SuccessBasedRoutingUpdateConfigQuery {
+ #[schema(value_type = String)]
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ #[schema(value_type = String)]
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+pub struct ToggleSuccessBasedRoutingWrapper {
+ pub profile_id: common_utils::id_type::ProfileId,
+ pub status: bool,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct ToggleSuccessBasedRoutingPath {
+ #[schema(value_type = String)]
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct SuccessBasedRoutingConfig {
+ pub params: Option<Vec<SuccessBasedRoutingConfigParams>>,
+ pub config: Option<SuccessBasedRoutingConfigBody>,
+}
+
+impl Default for SuccessBasedRoutingConfig {
+ fn default() -> Self {
+ Self {
+ params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]),
+ config: Some(SuccessBasedRoutingConfigBody {
+ min_aggregates_size: Some(2),
+ default_success_rate: Some(100.0),
+ max_aggregates_size: Some(3),
+ current_block_threshold: Some(CurrentBlockThreshold {
+ duration_in_mins: Some(5),
+ max_total_count: Some(2),
+ }),
+ }),
+ }
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub enum SuccessBasedRoutingConfigParams {
+ PaymentMethod,
+ PaymentMethodType,
+ Currency,
+ AuthenticationType,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct SuccessBasedRoutingConfigBody {
+ pub min_aggregates_size: Option<u32>,
+ pub default_success_rate: Option<f64>,
+ pub max_aggregates_size: Option<u32>,
+ pub current_block_threshold: Option<CurrentBlockThreshold>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct CurrentBlockThreshold {
+ pub duration_in_mins: Option<u64>,
+ pub max_total_count: Option<u64>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SuccessBasedRoutingPayloadWrapper {
+ pub updated_config: SuccessBasedRoutingConfig,
+ pub algorithm_id: common_utils::id_type::RoutingId,
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+impl SuccessBasedRoutingConfig {
+ pub fn update(&mut self, new: Self) {
+ if let Some(params) = new.params {
+ self.params = Some(params)
+ }
+ if let Some(new_config) = new.config {
+ self.config.as_mut().map(|config| config.update(new_config));
+ }
+ }
+}
+
+impl SuccessBasedRoutingConfigBody {
+ pub fn update(&mut self, new: Self) {
+ if let Some(min_aggregates_size) = new.min_aggregates_size {
+ self.min_aggregates_size = Some(min_aggregates_size)
+ }
+ if let Some(default_success_rate) = new.default_success_rate {
+ self.default_success_rate = Some(default_success_rate)
+ }
+ if let Some(max_aggregates_size) = new.max_aggregates_size {
+ self.max_aggregates_size = Some(max_aggregates_size)
+ }
+ if let Some(current_block_threshold) = new.current_block_threshold {
+ self.current_block_threshold
+ .as_mut()
+ .map(|threshold| threshold.update(current_block_threshold));
+ }
+ }
+}
+
+impl CurrentBlockThreshold {
+ pub fn update(&mut self, new: Self) {
+ if let Some(max_total_count) = new.max_total_count {
+ self.max_total_count = Some(max_total_count)
+ }
+ }
+}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 029add42ced..a72263b96a8 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -53,6 +53,7 @@ pub struct BusinessProfile {
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -129,6 +130,7 @@ pub struct BusinessProfileUpdateInternal {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -164,6 +166,7 @@ impl BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
} = self;
BusinessProfile {
profile_id: source.profile_id,
@@ -217,6 +220,8 @@ impl BusinessProfileUpdateInternal {
tax_connector_id: tax_connector_id.or(source.tax_connector_id),
is_tax_connector_enabled: is_tax_connector_enabled.or(source.is_tax_connector_enabled),
version: source.version,
+ dynamic_routing_algorithm: dynamic_routing_algorithm
+ .or(source.dynamic_routing_algorithm),
}
}
}
@@ -266,6 +271,7 @@ pub struct BusinessProfile {
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub id: common_utils::id_type::ProfileId,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
impl BusinessProfile {
@@ -452,6 +458,7 @@ impl BusinessProfileUpdateInternal {
.or(source.payout_routing_algorithm_id),
default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing),
version: source.version,
+ dynamic_routing_algorithm: None,
}
}
}
@@ -502,6 +509,7 @@ impl From<BusinessProfileNew> for BusinessProfile {
payout_routing_algorithm_id: new.payout_routing_algorithm_id,
default_fallback_routing: new.default_fallback_routing,
version: new.version,
+ dynamic_routing_algorithm: None,
}
}
}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 8f9469c0288..68809d8d2fa 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -50,6 +50,7 @@ pub enum RoutingAlgorithmKind {
Priority,
VolumeSplit,
Advanced,
+ Dynamic,
}
#[derive(
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8e6c72eb5ba..1487616f458 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -209,6 +209,7 @@ diesel::table! {
tax_connector_id -> Nullable<Varchar>,
is_tax_connector_enabled -> Nullable<Bool>,
version -> ApiVersion,
+ dynamic_routing_algorithm -> Nullable<Json>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 2deaa3d4ee4..818e7ecf01e 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -216,6 +216,7 @@ diesel::table! {
#[max_length = 64]
id -> Varchar,
version -> ApiVersion,
+ dynamic_routing_algorithm -> Nullable<Json>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index c6b76680d48..b13d79175c2 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -54,6 +54,7 @@ pub struct BusinessProfile {
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub version: common_enums::ApiVersion,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -90,6 +91,7 @@ pub struct BusinessProfileSetter {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -133,6 +135,7 @@ impl From<BusinessProfileSetter> for BusinessProfile {
tax_connector_id: value.tax_connector_id,
is_tax_connector_enabled: value.is_tax_connector_enabled,
version: consts::API_VERSION,
+ dynamic_routing_algorithm: value.dynamic_routing_algorithm,
}
}
}
@@ -178,6 +181,7 @@ pub struct BusinessProfileGeneralUpdate {
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
+ pub dynamic_routing_algorithm: Option<serde_json::Value>,
}
#[cfg(feature = "v1")]
@@ -188,6 +192,9 @@ pub enum BusinessProfileUpdate {
routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
},
+ DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm: Option<serde_json::Value>,
+ },
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
},
@@ -230,6 +237,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
} = *update;
Self {
@@ -263,6 +271,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
+ dynamic_routing_algorithm,
}
}
BusinessProfileUpdate::RoutingAlgorithmUpdate {
@@ -298,6 +307,41 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
+ },
+ BusinessProfileUpdate::DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm,
+ } => Self {
+ profile_name: None,
+ modified_at: now,
+ return_url: None,
+ enable_payment_response_hash: None,
+ payment_response_hash_key: None,
+ redirect_to_merchant_with_http_post: None,
+ webhook_details: None,
+ metadata: None,
+ routing_algorithm: None,
+ intent_fulfillment_time: None,
+ frm_routing_algorithm: None,
+ payout_routing_algorithm: None,
+ is_recon_enabled: None,
+ applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
+ authentication_connector_details: None,
+ payout_link_config: None,
+ is_extended_card_info_enabled: None,
+ extended_card_info_config: None,
+ is_connector_agnostic_mit_enabled: None,
+ use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
+ collect_billing_details_from_wallet_connector: None,
+ outgoing_webhook_custom_http_headers: None,
+ always_collect_billing_details_from_wallet_connector: None,
+ always_collect_shipping_details_from_wallet_connector: None,
+ tax_connector_id: None,
+ is_tax_connector_enabled: None,
+ dynamic_routing_algorithm,
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
@@ -331,6 +375,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
},
BusinessProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
@@ -364,6 +409,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
+ dynamic_routing_algorithm: None,
},
}
}
@@ -416,6 +462,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
+ dynamic_routing_algorithm: self.dynamic_routing_algorithm,
})
}
@@ -480,6 +527,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
version: item.version,
+ dynamic_routing_algorithm: item.dynamic_routing_algorithm,
})
}
.await
@@ -984,6 +1032,7 @@ impl super::behaviour::Conversion for BusinessProfile {
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
+ dynamic_routing_algorithm: None,
})
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 2926f47af9e..6c911fc9bbe 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -158,6 +158,8 @@ Never share your secret api keys. Keep them guarded and secure.
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
+ routes::routing::toggle_success_based_routing,
+ routes::routing::success_based_routing_update_configs,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
@@ -543,6 +545,13 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
+ api_models::routing::ToggleSuccessBasedRoutingQuery,
+ api_models::routing::SuccessBasedRoutingConfig,
+ api_models::routing::SuccessBasedRoutingConfigParams,
+ api_models::routing::SuccessBasedRoutingConfigBody,
+ api_models::routing::CurrentBlockThreshold,
+ api_models::routing::SuccessBasedRoutingUpdateConfigQuery,
+ api_models::routing::ToggleSuccessBasedRoutingPath,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 5e1e3f60c62..009708d860d 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -255,3 +255,56 @@ pub async fn routing_retrieve_default_config_for_profiles() {}
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Toggle success based dynamic routing for profile
+///
+/// Create a success based dynamic routing algorithm
+#[utoipa::path(
+ post,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/toggle",
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
+ ("status" = bool, Query, description = "Boolean value for mentioning the expected state of dynamic routing"),
+ ),
+ responses(
+ (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Toggle success based dynamic routing algprithm",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn toggle_success_based_routing() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Update config for success based dynamic routing
+///
+/// Update config for success based dynamic routing
+#[utoipa::path(
+ patch,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/config/:algorithm_id",
+ request_body = SuccessBasedRoutingConfig,
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "The unique identifier for a profile"),
+ ("algorithm_id" = String, Path, description = "The unique identifier for routing algorithm"),
+ ),
+ responses(
+ (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
+ (status = 400, description = "Request body is malformed"),
+ (status = 500, description = "Internal server error"),
+ (status = 404, description = "Resource missing"),
+ (status = 422, description = "Unprocessable request"),
+ (status = 403, description = "Forbidden"),
+ ),
+ tag = "Routing",
+ operation_id = "Update configs for success based dynamic routing algorithm",
+ security(("admin_api_key" = []))
+)]
+pub async fn success_based_routing_update_configs() {}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c0cb446b38f..eb357d80ad1 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -3471,6 +3471,7 @@ impl BusinessProfileCreateBridge for api::BusinessProfileCreate {
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
+ dynamic_routing_algorithm: None,
},
))
}
@@ -3818,6 +3819,7 @@ impl BusinessProfileUpdateBridge for api::BusinessProfileUpdate {
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
+ dynamic_routing_algorithm: self.dynamic_routing_algorithm,
},
)))
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index df2f8746e11..35cc811af65 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -922,12 +922,12 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest, PaymentData<F>> for Paymen
Some(helpers::PaymentExternalAuthenticationFlow::PostAuthenticationFlow {
authentication_id,
}) => {
- let authentication = authentication::perform_post_authentication(
+ let authentication = Box::pin(authentication::perform_post_authentication(
state,
key_store,
business_profile.clone(),
authentication_id.clone(),
- )
+ ))
.await?;
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication.authentication_status
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index fd58a2c571a..2ce75065673 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2,12 +2,13 @@ pub mod helpers;
pub mod transformers;
use api_models::{
- enums, mandates as mandates_api,
+ enums, mandates as mandates_api, routing,
routing::{self as routing_types, RoutingRetrieveQuery},
};
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
use hyperswitch_domain_models::{mandates, payment_address};
+use router_env::metrics::add_attributes;
use rustc_hash::FxHashSet;
#[cfg(feature = "payouts")]
@@ -411,42 +412,89 @@ pub async fn link_routing_config(
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
- let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
- .routing_algorithm
- .clone()
- .map(|val| val.parse_value("RoutingAlgorithmRef"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize routing algorithm ref from merchant account")?
- .unwrap_or_default();
-
- utils::when(routing_algorithm.algorithm_for != *transaction_type, || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: format!(
- "Cannot use {}'s routing algorithm for {} operation",
- routing_algorithm.algorithm_for, transaction_type
- ),
- })
- })?;
+ match routing_algorithm.kind {
+ diesel_models::enums::RoutingAlgorithmKind::Dynamic => {
+ let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize Dynamic routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ utils::when(
+ matches!(
+ dynamic_routing_ref.success_based_algorithm,
+ Some(routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(ref id),
+ timestamp: _
+ }) if id == &algorithm_id
+ ),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
- utils::when(
- routing_ref.algorithm_id == Some(algorithm_id.clone()),
- || {
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: "Algorithm is already active".to_string(),
- })
- },
- )?;
- routing_ref.update_algorithm_id(algorithm_id);
- helpers::update_business_profile_active_algorithm_ref(
- db,
- key_manager_state,
- &key_store,
- business_profile,
- routing_ref,
- transaction_type,
- )
- .await?;
+ dynamic_routing_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ dynamic_routing_ref,
+ )
+ .await?;
+ }
+ diesel_models::enums::RoutingAlgorithmKind::Single
+ | diesel_models::enums::RoutingAlgorithmKind::Priority
+ | diesel_models::enums::RoutingAlgorithmKind::Advanced
+ | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit => {
+ let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
+ .routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("RoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ utils::when(routing_algorithm.algorithm_for != *transaction_type, || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!(
+ "Cannot use {}'s routing algorithm for {} operation",
+ routing_algorithm.algorithm_for, transaction_type
+ ),
+ })
+ })?;
+
+ utils::when(
+ routing_ref.algorithm_id == Some(algorithm_id.clone()),
+ || {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already active".to_string(),
+ })
+ },
+ )?;
+ routing_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ routing_ref,
+ transaction_type,
+ )
+ .await?;
+ }
+ };
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(
@@ -1111,3 +1159,192 @@ pub async fn update_default_routing_config_for_profile(
},
))
}
+
+#[cfg(feature = "v1")]
+pub async fn toggle_success_based_routing(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ status: bool,
+ profile_id: common_utils::id_type::ProfileId,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+
+ let business_profile: domain::BusinessProfile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("BusinessProfile")
+ .change_context(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let mut success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to deserialize dynamic routing algorithm ref from business profile",
+ )?
+ .unwrap_or_default();
+
+ if status {
+ let default_success_based_routing_config = routing::SuccessBasedRoutingConfig::default();
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: business_profile.get_id().to_owned(),
+ merchant_id: merchant_account.get_id().to_owned(),
+ name: "Dynamic routing algorithm".to_string(),
+ description: None,
+ kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
+ algorithm_data: serde_json::json!(default_success_based_routing_config),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: common_enums::TransactionType::Payment,
+ };
+
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ success_based_dynamic_routing_algo_ref.update_algorithm_id(algorithm_id);
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ success_based_dynamic_routing_algo_ref,
+ )
+ .await?;
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ Ok(service_api::ApplicationResponse::Json(new_record))
+ } else {
+ let timestamp = common_utils::date_time::now_unix_timestamp();
+ match success_based_dynamic_routing_algo_ref.success_based_algorithm {
+ Some(algorithm_ref) => {
+ if let Some(algorithm_id) = algorithm_ref.algorithm_id {
+ let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: Some(
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: None,
+ timestamp,
+ },
+ ),
+ };
+
+ let record = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(
+ business_profile.get_id(),
+ &algorithm_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ let response = record.foreign_into();
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ dynamic_routing_algorithm,
+ )
+ .await?;
+
+ metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+
+ Ok(service_api::ApplicationResponse::Json(response))
+ } else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ }
+ }
+ None => Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?,
+ }
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn success_based_routing_update_configs(
+ state: SessionState,
+ request: routing_types::SuccessBasedRoutingConfig,
+ algorithm_id: common_utils::id_type::RoutingId,
+ profile_id: common_utils::id_type::ProfileId,
+) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ let db = state.store.as_ref();
+ let dynamic_routing_algo_to_update = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let mut config_to_update: routing::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update
+ .algorithm_data
+ .parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?;
+
+ config_to_update.update(request);
+
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = RoutingAlgorithm {
+ algorithm_id,
+ profile_id: dynamic_routing_algo_to_update.profile_id,
+ merchant_id: dynamic_routing_algo_to_update.merchant_id,
+ name: dynamic_routing_algo_to_update.name,
+ description: dynamic_routing_algo_to_update.description,
+ kind: dynamic_routing_algo_to_update.kind,
+ algorithm_data: serde_json::json!(config_to_update),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
+ };
+ let record = db
+ .insert_routing_algorithm(algo)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to insert record in routing algorithm table")?;
+
+ let new_record = record.foreign_into();
+
+ metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ Ok(service_api::ApplicationResponse::Json(new_record))
+}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index bd4107a48d0..f818dc05f5b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -236,6 +236,33 @@ pub async fn update_business_profile_active_algorithm_ref(
Ok(())
}
+#[cfg(feature = "v1")]
+pub async fn update_business_profile_active_dynamic_algorithm_ref(
+ db: &dyn StorageInterface,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ current_business_profile: domain::BusinessProfile,
+ dynamic_routing_algorithm: routing_types::DynamicRoutingAlgorithmRef,
+) -> RouterResult<()> {
+ let ref_val = dynamic_routing_algorithm
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert dynamic routing ref to value")?;
+ let business_profile_update = domain::BusinessProfileUpdate::DynamicRoutingAlgorithmUpdate {
+ dynamic_routing_algorithm: Some(ref_val),
+ };
+ db.update_business_profile_by_profile_id(
+ key_manager_state,
+ merchant_key_store,
+ current_business_profile,
+ business_profile_update,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update dynamic routing algorithm ref in business profile")?;
+ Ok(())
+}
+
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct RoutingAlgorithmHelpers<'h> {
diff --git a/crates/router/src/core/routing/transformers.rs b/crates/router/src/core/routing/transformers.rs
index 6bffde12a9b..652422086b7 100644
--- a/crates/router/src/core/routing/transformers.rs
+++ b/crates/router/src/core/routing/transformers.rs
@@ -72,6 +72,7 @@ impl ForeignFrom<storage_enums::RoutingAlgorithmKind> for RoutingAlgorithmKind {
storage_enums::RoutingAlgorithmKind::Priority => Self::Priority,
storage_enums::RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
storage_enums::RoutingAlgorithmKind::Advanced => Self::Advanced,
+ storage_enums::RoutingAlgorithmKind::Dynamic => Self::Dynamic,
}
}
}
@@ -83,6 +84,7 @@ impl ForeignFrom<RoutingAlgorithmKind> for storage_enums::RoutingAlgorithmKind {
RoutingAlgorithmKind::Priority => Self::Priority,
RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
RoutingAlgorithmKind::Advanced => Self::Advanced,
+ RoutingAlgorithmKind::Dynamic => Self::Dynamic,
}
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 210ded9c25d..0c6e6762854 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1614,6 +1614,23 @@ impl BusinessProfile {
)
.service(
web::scope("/{profile_id}")
+ .service(
+ web::scope("/dynamic_routing").service(
+ web::scope("/success_based")
+ .service(
+ web::resource("/toggle").route(
+ web::post().to(routing::toggle_success_based_routing),
+ ),
+ )
+ .service(web::resource("/config/{algorithm_id}").route(
+ web::patch().to(|state, req, path, payload| {
+ routing::success_based_routing_update_configs(
+ state, req, path, payload,
+ )
+ }),
+ )),
+ ),
+ )
.service(
web::resource("")
.route(web::get().to(business_profile_retrieve))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 13148801aa9..9593e0344c9 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -65,6 +65,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::RoutingDeleteConfig
| Flow::DecisionManagerDeleteConfig
| Flow::DecisionManagerRetrieveConfig
+ | Flow::ToggleDynamicRouting
+ | Flow::UpdateDynamicRoutingConfigs
| Flow::DecisionManagerUpsertConfig => Self::Routing,
Flow::RetrieveForexFlow => Self::Forex,
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index b1831068991..5870b5ba77d 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -977,3 +977,88 @@ pub async fn routing_update_default_config_for_profile(
))
.await
}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn toggle_success_based_routing(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_models::routing::ToggleSuccessBasedRoutingQuery>,
+ path: web::Path<routing_types::ToggleSuccessBasedRoutingPath>,
+) -> impl Responder {
+ let flow = Flow::ToggleDynamicRouting;
+ let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper {
+ status: query.into_inner().status,
+ profile_id: path.into_inner().profile_id,
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ wrapper.clone(),
+ |state,
+ auth: auth::AuthenticationData,
+ wrapper: routing_types::ToggleSuccessBasedRoutingWrapper,
+ _| {
+ routing::toggle_success_based_routing(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ wrapper.status,
+ wrapper.profile_id,
+ )
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn success_based_routing_update_configs(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<routing_types::SuccessBasedRoutingUpdateConfigQuery>,
+ json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>,
+) -> impl Responder {
+ let flow = Flow::UpdateDynamicRoutingConfigs;
+ let routing_payload_wrapper = routing_types::SuccessBasedRoutingPayloadWrapper {
+ updated_config: json_payload.into_inner(),
+ algorithm_id: path.clone().algorithm_id,
+ profile_id: path.clone().profile_id,
+ };
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ routing_payload_wrapper,
+ |state, _, wrapper: routing_types::SuccessBasedRoutingPayloadWrapper, _| async {
+ Box::pin(routing::success_based_routing_update_configs(
+ state,
+ wrapper.updated_config,
+ wrapper.algorithm_id,
+ wrapper.profile_id,
+ ))
+ .await
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 3d915f838ee..9d90ef530ae 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -347,6 +347,7 @@ pub async fn create_business_profile_from_merchant_account(
.map(Into::into),
tax_connector_id: request.tax_connector_id,
is_tax_connector_enabled: request.is_tax_connector_enabled,
+ dynamic_routing_algorithm: None,
},
))
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 79ab704fbbe..329fe5e55fc 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -242,6 +242,10 @@ pub enum Flow {
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
+ /// Toggle dynamic routing
+ ToggleDynamicRouting,
+ /// Update dynamic routing config
+ UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
diff --git a/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql
new file mode 100644
index 00000000000..9ca7ff5389e
--- /dev/null
+++ b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+DELETE FROM pg_enum
+WHERE enumlabel = 'dynamic'
+AND enumtypid = (
+ SELECT oid FROM pg_type WHERE typname = 'RoutingAlgorithmKind'
+);
diff --git a/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql
new file mode 100644
index 00000000000..ebe6188c7db
--- /dev/null
+++ b/migrations/2024-09-05-155712_add_new_variant_in_routing_algorithm_kind_type/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TYPE "RoutingAlgorithmKind" ADD VALUE 'dynamic';
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql
new file mode 100644
index 00000000000..61c22e45eae
--- /dev/null
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile
+DROP COLUMN dynamic_routing_algorithm;
diff --git a/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
new file mode 100644
index 00000000000..2482fc9f591
--- /dev/null
+++ b/migrations/2024-09-05-160455_add_new_col_is_dynamic_routing_algorithm_in_business_profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE business_profile
+ADD COLUMN dynamic_routing_algorithm JSON DEFAULT NULL;
| 2024-09-06T15:35:56Z |
## Description
<!-- Describe your changes in detail -->
### Toggle Success based dynamic routing
This PR will toggle success based dynamic routing for a profile, and the flow looks something like this:
1. A default config will be created for the profile, which will look something like this.
```
api_models::routing::SuccessBasedRoutingConfig {
params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(2),
default_success_rate: Some(100.0),
max_aggregates_size: Some(3),
current_block_threshold: Some(CurrentBlockThreshold {
duration_in_mins: Some(5),
max_total_count: Some(2),
}),
}),
};
```
2. `is_dynamic_routing_enabled` will be set to true in the business profile table and the routing algo id will be set.
The curls will be something like this:
1. Toggle(enable) Dynamic Routing.
```
curl --location --request POST 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/toggle?status=true' \
--header 'api-key: xxxxxx'
```
### Update success based dynamic routing configs
This route will update the default configs for success based dynamic routing for a particular profile. Basically it will create a new routing rule and assign the id in business_profile.
The authentication is `admin_api_key`
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/config/routing_LYmOkYZuaVkL6ZEXaAjA' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 1,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
4. `crates/router/src/configs`
5. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Baby steps for Dynamic Routing
## How did you test it?
1. Request:
```
curl --location --request POST 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/toggle?status=false' \
--header 'api-key:xxxxx'
```
Response:
```
{
"id": "routing_sSePmUaucfVIcaSeZPK4",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the BusinessProfile table for the `profile_id` and then whether the `dynamic_routing_algorithm` is present with the routing algo id we got in the response.
-> Toggle off the above curl by sending the `status` flag as `false` and then check the `step 1.` field for dynamic routing id to only have `timestamp` and no `routing_algorithm_Id`.
2. Request:
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/config/routing_LYmOkYZuaVkL6ZEXaAjA' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 1,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
Response:
```
{
"id": "routing_LYmOkYZuaVkL6ZEXaAjA",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the `RoutingAlgorithm` table for the `routing_algo_id`. Have a look for the fields above which we are updating like
`"max_total_count": 22` should be present. | 246fdc84064367885596b33f5e0e66af78a97a3c | 1. Request:
```
curl --location --request POST 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/toggle?status=false' \
--header 'api-key:xxxxx'
```
Response:
```
{
"id": "routing_sSePmUaucfVIcaSeZPK4",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the BusinessProfile table for the `profile_id` and then whether the `dynamic_routing_algorithm` is present with the routing algo id we got in the response.
-> Toggle off the above curl by sending the `status` flag as `false` and then check the `step 1.` field for dynamic routing id to only have `timestamp` and no `routing_algorithm_Id`.
2. Request:
```
curl --location --request PATCH 'http://localhost:8080/account/merchant_1726160910/business_profile/pro_7Oo0CzTQoOwE5HfwKf6v/dynamic_routing/success_based/config/routing_LYmOkYZuaVkL6ZEXaAjA' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"params": [
"Currency"
],
"config": {
"min_aggregates_size": 1,
"current_block_threshold": {
"max_total_count": 22
}
}
}'
```
Response:
```
{
"id": "routing_LYmOkYZuaVkL6ZEXaAjA",
"profile_id": "pro_ejL5TRsd1mjCulBMXFIR",
"name": "Dynamic routing algorithm",
"kind": "dynamic",
"description": "",
"created_at": 1725635764,
"modified_at": 1725635764,
"algorithm_for": "payment"
}
```
Things to check for:
-> Check the `RoutingAlgorithm` table for the `routing_algo_id`. Have a look for the fields above which we are updating like
`"max_total_count": 22` should be present.
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/admin.rs",
"crates/api_models/src/events/routing.rs",
"crates/api_models/src/routing.rs",
"crates/diesel_models/src/business_profile.rs",
"crates/diesel_models/src/enums.rs",
"crates/diesel_models/src/schema.rs",
"crates/diesel_models/src/sc... | |
juspay/hyperswitch | juspay__hyperswitch-5838 | Bug: [REFACTOR] update auth data for recon APIs
### Refactor Description
Refactor the code to
- pass only the required authentication data to recon APIs (remove UserFromToken which contains different resource IDs)
- remove existing impls for fetching user from DB
### 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/recon.rs b/crates/router/src/core/recon.rs
index fa9944ee8ee..2c2dfc9c9f0 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -17,11 +17,10 @@ use crate::{
pub async fn send_recon_request(
state: SessionState,
- user_with_auth_data: authentication::UserFromTokenWithAuthData,
+ auth_data: authentication::AuthenticationDataWithUser,
) -> RouterResponse<recon_api::ReconStatusResponse> {
- let user = user_with_auth_data.0;
- let user_in_db = &user_with_auth_data.1.user;
- let merchant_id = user.merchant_id;
+ let user_in_db = &auth_data.user;
+ let merchant_id = auth_data.merchant_account.get_id().clone();
let user_email = user_in_db.email.clone();
let email_contents = email_types::ProFeatureRequest {
@@ -55,7 +54,6 @@ pub async fn send_recon_request(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]")
.async_and_then(|_| async {
- let auth = user_with_auth_data.1;
let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
recon_status: enums::ReconStatus::Requested,
};
@@ -65,9 +63,9 @@ pub async fn send_recon_request(
let response = db
.update_merchant(
key_manager_state,
- auth.merchant_account,
+ auth_data.merchant_account,
updated_merchant_account,
- &auth.key_store,
+ &auth_data.key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 31ab0e8ff22..09d7ef8458c 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1823,11 +1823,9 @@ pub async fn verify_token(
state: SessionState,
user: auth::UserFromToken,
) -> UserResponse<user_api::VerifyTokenResponse> {
- let user_in_db = state
- .global_store
- .find_user_by_id(&user.user_id)
+ let user_in_db = user
+ .get_user_from_db(&state)
.await
- .change_context(UserErrors::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to fetch the user from DB for user_id - {}",
@@ -1837,7 +1835,7 @@ pub async fn verify_token(
Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse {
merchant_id: user.merchant_id.to_owned(),
- user_email: user_in_db.email,
+ user_email: user_in_db.0.email,
}))
}
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 34097b6bac6..e112d543960 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -575,7 +575,10 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques
&http_req,
(),
|state, user, _req, _| user_core::verify_token(state, user),
- &auth::DashboardNoPermissionAuth,
+ &auth::JWTAuth {
+ permission: Permission::ReconAdmin,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 5f9fc798d89..d8318ce9517 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1984,13 +1984,9 @@ where
default_auth
}
-#[derive(Clone)]
-#[cfg(feature = "recon")]
-pub struct UserFromTokenWithAuthData(pub UserFromToken, pub AuthenticationDataWithUser);
-
#[cfg(feature = "recon")]
#[async_trait]
-impl<A> AuthenticateAndFetch<UserFromTokenWithAuthData, A> for JWTAuth
+impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
@@ -1998,7 +1994,7 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<(UserFromTokenWithAuthData, AuthenticationType)> {
+ ) -> RouterResult<(AuthenticationDataWithUser, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
@@ -2049,17 +2045,9 @@ where
let auth_type = AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.get_id().clone(),
- user_id: Some(user_id.clone()),
- };
-
- let user = UserFromToken {
- user_id,
- merchant_id: payload.merchant_id.clone(),
- org_id: payload.org_id,
- role_id: payload.role_id,
- profile_id: payload.profile_id,
+ user_id: Some(user_id),
};
- Ok((UserFromTokenWithAuthData(user, auth), auth_type))
+ Ok((auth, auth_type))
}
}
| 2024-09-06T13:53:29Z |
## Description
Described in #5838
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Helps removing redundant code.
## How did you test it?
<details>
<summary>1. Request a new JWT token for recon dashboard</summary>
cURL Request
curl --location 'http://localhost:8080/recon/token' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTcwNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.aepFkZLGZUYHGY0R0dSNsvevrZodDtfwfEDyriBiti0' \
--data ''
Response
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs"
}
</details>
<details>
<summary>2. Verify this recon token</summary>
cURL Request
curl --location 'http://localhost:8080/recon/verify_token' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs' \
--data ''
Response
{
"merchant_id": "merchant_1725560588",
"user_email": "example@example.com"
}
</details>
<details>
<summary>3. Switch the merchant on dashboard from the same user and request a new JWT token for recon dashboard</summary>
cURL Request
curl --location 'http://localhost:8080/recon/token' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgyNSwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.nZtXfvFWUC7FfAbNQ_IouE5zjWxYd8fahXhzR4bs_oQ' \
--data ''
Response
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk"
}
</details>
<details>
<summary>4. Verify this token (it should have switched merchant's ID)</summary>
cURL Request
curl --location 'http://localhost:8080/recon/verify_token' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk' \
--data ''
Response
{
"merchant_id": "merchant_1725560754",
"user_email": "example@example.com"
}
</details> | aa2f5d147561f6e996228d269e6a54c5d1f53a60 | <details>
<summary>1. Request a new JWT token for recon dashboard</summary>
cURL Request
curl --location 'http://localhost:8080/recon/token' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTcwNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.aepFkZLGZUYHGY0R0dSNsvevrZodDtfwfEDyriBiti0' \
--data ''
Response
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs"
}
</details>
<details>
<summary>2. Verify this recon token</summary>
cURL Request
curl --location 'http://localhost:8080/recon/verify_token' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs' \
--data ''
Response
{
"merchant_id": "merchant_1725560588",
"user_email": "example@example.com"
}
</details>
<details>
<summary>3. Switch the merchant on dashboard from the same user and request a new JWT token for recon dashboard</summary>
cURL Request
curl --location 'http://localhost:8080/recon/token' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgyNSwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.nZtXfvFWUC7FfAbNQ_IouE5zjWxYd8fahXhzR4bs_oQ' \
--data ''
Response
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk"
}
</details>
<details>
<summary>4. Verify this token (it should have switched merchant's ID)</summary>
cURL Request
curl --location 'http://localhost:8080/recon/verify_token' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk' \
--data ''
Response
{
"merchant_id": "merchant_1725560754",
"user_email": "example@example.com"
}
</details>
| [
"crates/router/src/core/recon.rs",
"crates/router/src/core/user.rs",
"crates/router/src/routes/user.rs",
"crates/router/src/services/authentication.rs"
] | |
juspay/hyperswitch | juspay__hyperswitch-5858 | Bug: [FEATURE] [DEUTSCHEBANK] Integrate SEPA Payments
### Feature Description
Integrate SEPA Payments for connector Deutsche Bank
### Possible Implementation
https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html#chap_sdd
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index bda5fab29c0..acff517e107 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -4979,6 +4979,7 @@
"cryptopay",
"cybersource",
"datatrans",
+ "deutschebank",
"dlocal",
"ebanx",
"fiserv",
@@ -17213,6 +17214,7 @@
"cryptopay",
"cybersource",
"datatrans",
+ "deutschebank",
"dlocal",
"ebanx",
"fiserv",
diff --git a/config/config.example.toml b/config/config.example.toml
index 4c543fbdec3..7059626f8cf 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -201,7 +201,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -411,6 +411,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi = { payment_method = "card" }
payme = { payment_method = "card" }
+deutschebank = { payment_method = "bank_debit" }
[dummy_connector]
enabled = true # Whether dummy connector is enabled or not
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 4f109fc612c..90d29a6992d 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -43,7 +43,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -346,6 +346,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi.payment_method = "card"
payme.payment_method = "card"
+deutschebank = { payment_method = "bank_debit" }
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 9c387aa10af..0443d191542 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -48,7 +48,7 @@ cryptopay.base_url = "https://business.cryptopay.me/"
cybersource.base_url = "https://api.cybersource.com/"
datatrans.base_url = "https://api.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
-deutschebank.base_url = "https://merch.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://merch.directpos.de/rest-api"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
@@ -359,6 +359,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi.payment_method = "card"
payme.payment_method = "card"
+deutschebank = { payment_method = "bank_debit" }
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 706bcb6e1b9..8c679241729 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -48,7 +48,7 @@ cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
fiserv.base_url = "https://cert.api.fiservapps.com/"
@@ -363,6 +363,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi.payment_method = "card"
payme.payment_method = "card"
+deutschebank = { payment_method = "bank_debit" }
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/development.toml b/config/development.toml
index 0b6c1c76909..1c6a4a827f3 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -210,7 +210,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -538,6 +538,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi = { payment_method = "card" }
payme = { payment_method = "card" }
+deutschebank = { payment_method = "bank_debit" }
[connector_customer]
connector_list = "gocardless,stax,stripe"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index bc1be36f82c..704acdfee14 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -130,7 +130,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -317,6 +317,7 @@ bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi = { payment_method = "card" }
payme = { payment_method = "card" }
+deutschebank = { payment_method = "bank_debit" }
[dummy_connector]
enabled = true
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 2826608b639..64af2349f7c 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -94,7 +94,7 @@ pub enum Connector {
Cryptopay,
Cybersource,
Datatrans,
- // Deutschebank,
+ Deutschebank,
Dlocal,
Ebanx,
Fiserv,
@@ -187,6 +187,7 @@ impl Connector {
matches!(
(self, payment_method),
(Self::Airwallex, _)
+ | (Self::Deutschebank, _)
| (Self::Globalpay, _)
| (Self::Paypal, _)
| (Self::Payu, _)
@@ -231,7 +232,7 @@ impl Connector {
| Self::Cashtocode
| Self::Coinbase
| Self::Cryptopay
- // | Self::Deutschebank
+ | Self::Deutschebank
| Self::Dlocal
| Self::Ebanx
| Self::Fiserv
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index b6500d79b84..10c9dae2cc1 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -208,7 +208,7 @@ pub enum RoutableConnectors {
Cryptopay,
Cybersource,
Datatrans,
- // Deutschebank,
+ Deutschebank,
Dlocal,
Ebanx,
Fiserv,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index fb4d92581ed..3ead246702c 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -171,6 +171,7 @@ pub struct ConnectorConfig {
pub opennode: Option<ConnectorTomlConfig>,
pub bambora: Option<ConnectorTomlConfig>,
pub datatrans: Option<ConnectorTomlConfig>,
+ pub deutschebank: Option<ConnectorTomlConfig>,
pub dlocal: Option<ConnectorTomlConfig>,
pub ebanx_payout: Option<ConnectorTomlConfig>,
pub fiserv: Option<ConnectorTomlConfig>,
@@ -322,6 +323,7 @@ impl ConnectorConfig {
Connector::Opennode => Ok(connector_data.opennode),
Connector::Bambora => Ok(connector_data.bambora),
Connector::Datatrans => Ok(connector_data.datatrans),
+ Connector::Deutschebank => Ok(connector_data.deutschebank),
Connector::Dlocal => Ok(connector_data.dlocal),
Connector::Ebanx => Ok(connector_data.ebanx_payout),
Connector::Fiserv => Ok(connector_data.fiserv),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index ef2cf56f31b..41bcb52704a 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1353,6 +1353,14 @@ api_key="Key"
key1="Merchant ID"
api_secret="Shared Secret"
+[deutschebank]
+[[deutschebank.bank_debit]]
+ payment_method_type = "sepa"
+[deutschebank.connector_auth.SignatureKey]
+api_key="Client ID"
+key1="Merchant ID"
+api_secret="Client Key"
+
[dlocal]
[[dlocal.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index c7e55ca7a79..8d6d2d3a5c6 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1125,6 +1125,14 @@ placeholder="Enter Acquirer Country Code"
required=false
type="Text"
+[deutschebank]
+[[deutschebank.bank_debit]]
+ payment_method_type = "sepa"
+[deutschebank.connector_auth.SignatureKey]
+api_key="Client ID"
+key1="Merchant ID"
+api_secret="Client Key"
+
[dlocal]
[[dlocal.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 9d44f76970f..165682b7501 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1352,6 +1352,14 @@ api_key="Key"
key1="Merchant ID"
api_secret="Shared Secret"
+[deutschebank]
+[[deutschebank.bank_debit]]
+ payment_method_type = "sepa"
+[deutschebank.connector_auth.SignatureKey]
+api_key="Client ID"
+key1="Merchant ID"
+api_secret="Client Key"
+
[dlocal]
[[dlocal.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
index 3d7e55c3a90..30e67babe89 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs
@@ -1,27 +1,36 @@
pub mod transformers;
+use std::time::SystemTime;
+
+use actix_web::http::header::Date;
+use base64::Engine;
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
- types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+ types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
- payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ payments::{
+ Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session,
+ SetupMandate, Void,
+ },
refunds::{Execute, RSync},
},
router_request_types::{
- AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
- RefundsData, SetupMandateRequestData,
+ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
- PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
@@ -33,20 +42,26 @@ use hyperswitch_interfaces::{
types::{self, Response},
webhooks,
};
-use masking::{ExposeInterface, Mask};
+use masking::{ExposeInterface, Mask, Secret};
+use rand::distributions::{Alphanumeric, DistString};
+use ring::hmac;
use transformers as deutschebank;
-use crate::{constants::headers, types::ResponseRouterData, utils};
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, PaymentsCompleteAuthorizeRequestData, RefundsRequestData},
+};
#[derive(Clone)]
pub struct Deutschebank {
- amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+ amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Deutschebank {
pub fn new() -> &'static Self {
&Self {
- amount_converter: &StringMinorUnitForConnector,
+ amount_converter: &MinorUnitForConnector,
}
}
}
@@ -56,6 +71,7 @@ impl api::PaymentSession for Deutschebank {}
impl api::ConnectorAccessToken for Deutschebank {}
impl api::MandateSetup for Deutschebank {}
impl api::PaymentAuthorize for Deutschebank {}
+impl api::PaymentsCompleteAuthorize for Deutschebank {}
impl api::PaymentSync for Deutschebank {}
impl api::PaymentCapture for Deutschebank {}
impl api::PaymentVoid for Deutschebank {}
@@ -79,10 +95,20 @@ where
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- let mut header = vec![(
- headers::CONTENT_TYPE.to_string(),
- self.get_content_type().to_string().into(),
- )];
+ let access_token = req
+ .access_token
+ .clone()
+ .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
+ let mut header = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ ),
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", access_token.token.expose()).into_masked(),
+ ),
+ ];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
@@ -96,9 +122,6 @@ impl ConnectorCommon for Deutschebank {
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
- // TODO! Check connector documentation, on which unit they are processing the currency.
- // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
- // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
@@ -116,8 +139,8 @@ impl ConnectorCommon for Deutschebank {
let auth = deutschebank::DeutschebankAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
+ headers::MERCHANT_ID.to_string(),
+ auth.merchant_id.expose().into_masked(),
)])
}
@@ -136,9 +159,9 @@ impl ConnectorCommon for Deutschebank {
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.rc,
+ message: response.message.clone(),
+ reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
})
@@ -146,20 +169,124 @@ impl ConnectorCommon for Deutschebank {
}
impl ConnectorValidation for Deutschebank {
- //TODO: implement functions when support enabled
+ fn validate_capture_method(
+ &self,
+ capture_method: Option<enums::CaptureMethod>,
+ _pmt: Option<enums::PaymentMethodType>,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let capture_method = capture_method.unwrap_or_default();
+ match capture_method {
+ enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()),
+ enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
+ ),
+ }
+ }
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank {}
-
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Deutschebank
{
}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank {
+ fn get_url(
+ &self,
+ _req: &RefreshTokenRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/security/v1/token", self.base_url(connectors)))
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ "application/x-www-form-urlencoded"
+ }
+
+ fn build_request(
+ &self,
+ req: &RefreshTokenRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let auth = deutschebank::DeutschebankAuthType::try_from(&req.connector_auth_type)?;
+ let client_id = auth.client_id.expose();
+ let date = Date(SystemTime::now().into()).to_string();
+ let random_string = Alphanumeric.sample_string(&mut rand::thread_rng(), 50);
+
+ let string_to_sign = client_id.clone() + &date + &random_string;
+ let key = hmac::Key::new(hmac::HMAC_SHA256, auth.client_key.expose().as_bytes());
+ let client_secret = format!(
+ "V1:{}",
+ common_utils::consts::BASE64_ENGINE
+ .encode(hmac::sign(&key, string_to_sign.as_bytes()).as_ref())
+ );
+
+ let headers = vec![
+ (
+ headers::X_RANDOM_VALUE.to_string(),
+ random_string.into_masked(),
+ ),
+ (headers::X_REQUEST_DATE.to_string(), date.into_masked()),
+ (
+ headers::CONTENT_TYPE.to_string(),
+ types::RefreshTokenType::get_content_type(self)
+ .to_string()
+ .into(),
+ ),
+ ];
+
+ let connector_req = deutschebank::DeutschebankAccessTokenRequest {
+ client_id: Secret::from(client_id),
+ client_secret: Secret::from(client_secret),
+ grant_type: "client_credentials".to_string(),
+ scope: "ftx".to_string(),
+ };
+ let body = RequestContent::FormUrlEncoded(Box::new(connector_req));
+
+ let req = Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .headers(headers)
+ .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
+ .set_body(body)
+ .build(),
+ );
+ Ok(req)
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefreshTokenRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
+ let response: deutschebank::DeutschebankAccessTokenResponse = res
+ .response
+ .parse_struct("Paypal PaypalAuthUpdateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
@@ -176,9 +303,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!(
+ "{}/services/v2.1/managedmandate",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
@@ -226,7 +356,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: deutschebank::DeutschebankPaymentsResponse = res
+ let response: deutschebank::DeutschebankMandatePostResponse = res
.response
.parse_struct("Deutschebank PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -248,6 +378,105 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
}
}
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Deutschebank
+{
+ fn get_headers(
+ &self,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let event_id = req.connector_request_reference_id.clone();
+ let tx_action = if req.request.is_auto_capture()? {
+ "authorization"
+ } else {
+ "preauthorization"
+ };
+ Ok(format!(
+ "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req));
+ let connector_req =
+ deutschebank::DeutschebankDirectDebitRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ let response: deutschebank::DeutschebankPaymentsResponse = res
+ .response
+ .parse_struct("Deutschebank PaymentsCompleteAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deutschebank {
fn get_headers(
&self,
@@ -263,10 +492,18 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deu
fn get_url(
&self,
- _req: &PaymentsSyncRouterData,
- _connectors: &Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let tx_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/services/v2.1/payment/tx/{tx_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -292,7 +529,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deu
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: deutschebank::DeutschebankPaymentsResponse = res
.response
- .parse_struct("deutschebank PaymentsSyncResponse")
+ .parse_struct("DeutschebankPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -327,18 +564,32 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
fn get_url(
&self,
- _req: &PaymentsCaptureRouterData,
- _connectors: &Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let event_id = req.connector_request_reference_id.clone();
+ let tx_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/capture",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
&self,
- _req: &PaymentsCaptureRouterData,
+ req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req));
+ let connector_req =
+ deutschebank::DeutschebankCaptureRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -389,7 +640,86 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
}
}
-impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Deutschebank {}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Deutschebank {
+ fn get_headers(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let event_id = req.connector_request_reference_id.clone();
+ let tx_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/reversal",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = deutschebank::DeutschebankReversalRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsVoidType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCancelRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: deutschebank::DeutschebankPaymentsResponse = res
+ .response
+ .parse_struct("Deutschebank PaymentsCancelResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutschebank {
fn get_headers(
@@ -406,10 +736,15 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutsch
fn get_url(
&self,
- _req: &RefundsRouterData<Execute>,
- _connectors: &Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let event_id = req.attempt_id.clone();
+ let tx_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/refund",
+ self.base_url(connectors)
+ ))
}
fn get_request_body(
@@ -455,9 +790,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutsch
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
- let response: deutschebank::RefundResponse = res
+ let response: deutschebank::DeutschebankPaymentsResponse = res
.response
- .parse_struct("deutschebank RefundResponse")
+ .parse_struct("DeutschebankPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -492,10 +827,14 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Deutscheb
fn get_url(
&self,
- _req: &RefundSyncRouterData,
- _connectors: &Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let tx_id = req.request.get_connector_refund_id()?;
+ Ok(format!(
+ "{}/services/v2.1/payment/tx/{tx_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -522,9 +861,9 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Deutscheb
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
- let response: deutschebank::RefundResponse = res
+ let response: deutschebank::DeutschebankPaymentsResponse = res
.response
- .parse_struct("deutschebank RefundSyncResponse")
+ .parse_struct("DeutschebankPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
index aca2bd497b6..dc146dc38d4 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
@@ -1,31 +1,43 @@
+use std::collections::HashMap;
+
use common_enums::enums;
-use common_utils::types::StringMinorUnit;
+use common_utils::{pii::Email, types::MinorUnit};
use hyperswitch_domain_models::{
- payment_method_data::PaymentMethodData,
- router_data::{ConnectorAuthType, RouterData},
- router_flow_types::refunds::{Execute, RSync},
- router_request_types::ResponseId,
- router_response_types::{PaymentsResponseData, RefundsResponseData},
- types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+ payment_method_data::{BankDebitData, PaymentMethodData},
+ router_data::{AccessToken, ConnectorAuthType, RouterData},
+ router_flow_types::{
+ payments::{Authorize, Capture, CompleteAuthorize, PSync},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
+ ResponseId,
+ },
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
+ },
};
use hyperswitch_interfaces::errors;
-use masking::Secret;
+use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- types::{RefundsResponseRouterData, ResponseRouterData},
- utils::PaymentsAuthorizeRequestData,
+ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+ RefundsRequestData, RouterData as OtherRouterData,
+ },
};
-//TODO: Fill the struct with respective fields
pub struct DeutschebankRouterData<T> {
- pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: MinorUnit,
pub router_data: T,
}
-impl<T> From<(StringMinorUnit, T)> for DeutschebankRouterData<T> {
- fn from((amount, item): (StringMinorUnit, T)) -> Self {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
+impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> {
+ fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
@@ -33,20 +45,80 @@ impl<T> From<(StringMinorUnit, T)> for DeutschebankRouterData<T> {
}
}
-//TODO: Fill the struct with respective fields
+pub struct DeutschebankAuthType {
+ pub(super) client_id: Secret<String>,
+ pub(super) merchant_id: Secret<String>,
+ pub(super) client_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => Ok(Self {
+ client_id: api_key.to_owned(),
+ merchant_id: key1.to_owned(),
+ client_key: api_secret.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+
#[derive(Default, Debug, Serialize, PartialEq)]
-pub struct DeutschebankPaymentsRequest {
- amount: StringMinorUnit,
- card: DeutschebankCard,
+pub struct DeutschebankAccessTokenRequest {
+ pub grant_type: String,
+ pub client_id: Secret<String>,
+ pub client_secret: Secret<String>,
+ pub scope: String,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct DeutschebankCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)]
+pub struct DeutschebankAccessTokenResponse {
+ pub access_token: Secret<String>,
+ pub expires_in: i64,
+ pub expires_on: i64,
+ pub scope: String,
+ pub token_type: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>>
+ for RouterData<F, T, AccessToken>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(AccessToken {
+ token: item.response.access_token,
+ expires: item.response.expires_in,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum DeutschebankSEPAApproval {
+ Click,
+ Email,
+ Sms,
+ Dynamic,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankPaymentsRequest {
+ approval_by: DeutschebankSEPAApproval,
+ email_address: Email,
+ iban: Secret<String>,
+ first_name: Secret<String>,
+ last_name: Secret<String>,
}
impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
@@ -56,81 +128,315 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>>
fn try_from(
item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
+ let billing_address = item.router_data.get_billing_address()?;
match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::Card(req_card) => {
- let card = DeutschebankCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
- };
- Ok(Self {
- amount: item.amount.clone(),
- card,
- })
- }
+ PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Self {
+ approval_by: DeutschebankSEPAApproval::Click,
+ email_address: item.router_data.request.get_email()?,
+ iban,
+ first_name: billing_address.get_first_name()?.clone(),
+ last_name: billing_address.get_last_name()?.clone(),
+ }),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
-pub struct DeutschebankAuthType {
- pub(super) api_key: Secret<String>,
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum DeutschebankSEPAMandateStatus {
+ Created,
+ PendingApproval,
+ PendingSecondaryApproval,
+ PendingReview,
+ PendingSubmission,
+ Submitted,
+ Active,
+ Failed,
+ Discarded,
+ Expired,
+ Replaced,
}
-impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType {
+impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus {
+ fn from(item: DeutschebankSEPAMandateStatus) -> Self {
+ match item {
+ DeutschebankSEPAMandateStatus::Active
+ | DeutschebankSEPAMandateStatus::Created
+ | DeutschebankSEPAMandateStatus::PendingApproval
+ | DeutschebankSEPAMandateStatus::PendingSecondaryApproval
+ | DeutschebankSEPAMandateStatus::PendingReview
+ | DeutschebankSEPAMandateStatus::PendingSubmission
+ | DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending,
+ DeutschebankSEPAMandateStatus::Failed
+ | DeutschebankSEPAMandateStatus::Discarded
+ | DeutschebankSEPAMandateStatus::Expired
+ | DeutschebankSEPAMandateStatus::Replaced => Self::Failure,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct DeutschebankMandatePostResponse {
+ rc: String,
+ message: String,
+ mandate_id: Option<String>,
+ reference: Option<String>,
+ approval_date: Option<String>,
+ language: Option<String>,
+ approval_by: Option<DeutschebankSEPAApproval>,
+ state: Option<DeutschebankSEPAMandateStatus>,
+}
+
+impl
+ TryFrom<
+ ResponseRouterData<
+ Authorize,
+ DeutschebankMandatePostResponse,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
- match auth_type {
- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ fn try_from(
+ item: ResponseRouterData<
+ Authorize,
+ DeutschebankMandatePostResponse,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let signed_on = match item.response.approval_date {
+ Some(date) => date.chars().take(10).collect(),
+ None => time::OffsetDateTime::now_utc().date().to_string(),
+ };
+ match item.response.reference {
+ Some(reference) => Ok(Self {
+ status: if item.response.rc == "0" {
+ match item.response.state {
+ Some(state) => common_enums::AttemptStatus::from(state),
+ None => common_enums::AttemptStatus::Failure,
+ }
+ } else {
+ common_enums::AttemptStatus::Failure
+ },
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
+ redirection_data: Some(RedirectForm::Form {
+ endpoint: item.data.request.get_complete_authorize_url()?,
+ method: common_utils::request::Method::Get,
+ form_fields: HashMap::from([
+ ("reference".to_string(), reference),
+ ("signed_on".to_string(), signed_on),
+ ]),
+ }),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ None => Ok(Self {
+ status: common_enums::AttemptStatus::Failure,
+ ..item.data
}),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum DeutschebankPaymentStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+pub struct DeutschebankAmount {
+ amount: MinorUnit,
+ currency: api_models::enums::Currency,
}
-impl From<DeutschebankPaymentStatus> for common_enums::AttemptStatus {
- fn from(item: DeutschebankPaymentStatus) -> Self {
- match item {
- DeutschebankPaymentStatus::Succeeded => Self::Charged,
- DeutschebankPaymentStatus::Failed => Self::Failure,
- DeutschebankPaymentStatus::Processing => Self::Authorizing,
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankMeansOfPayment {
+ bank_account: DeutschebankBankAccount,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankBankAccount {
+ account_holder: Secret<String>,
+ iban: Secret<String>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankMandate {
+ reference: Secret<String>,
+ signed_on: Secret<String>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankDirectDebitRequest {
+ amount_total: DeutschebankAmount,
+ means_of_payment: DeutschebankMeansOfPayment,
+ mandate: DeutschebankMandate,
+}
+
+impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>>
+ for DeutschebankDirectDebitRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let account_holder = item.router_data.get_billing_address()?.get_full_name()?;
+ let redirect_response = item.router_data.request.redirect_response.clone().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "redirect_response",
+ },
+ )?;
+ let queries_params = redirect_response
+ .params
+ .map(|param| {
+ let mut queries = HashMap::<String, String>::new();
+ let values = param.peek().split('&').collect::<Vec<&str>>();
+ for value in values {
+ let pair = value.split('=').collect::<Vec<&str>>();
+ queries.insert(
+ pair.first()
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
+ .to_string(),
+ pair.get(1)
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
+ .to_string(),
+ );
+ }
+ Ok::<_, errors::ConnectorError>(queries)
+ })
+ .transpose()?
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let reference = Secret::from(
+ queries_params
+ .get("reference")
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "reference",
+ })?
+ .to_owned(),
+ );
+ let signed_on = Secret::from(
+ queries_params
+ .get("signed_on")
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "signed_on",
+ })?
+ .to_owned(),
+ );
+
+ match item.router_data.request.payment_method_data.clone() {
+ Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => {
+ Ok(Self {
+ amount_total: DeutschebankAmount {
+ amount: item.amount,
+ currency: item.router_data.request.currency,
+ },
+ means_of_payment: DeutschebankMeansOfPayment {
+ bank_account: DeutschebankBankAccount {
+ account_holder,
+ iban,
+ },
+ },
+ mandate: {
+ DeutschebankMandate {
+ reference,
+ signed_on,
+ }
+ },
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum DeutschebankTXAction {
+ Authorization,
+ Capture,
+ Credit,
+ Preauthorization,
+ Refund,
+ Reversal,
+ RiskCheck,
+ #[serde(rename = "verify-mop")]
+ VerifyMop,
+ Payment,
+ AccountInformation,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+pub struct BankAccount {
+ account_holder: Option<Secret<String>>,
+ bank_name: Option<Secret<String>>,
+ bic: Option<Secret<String>>,
+ iban: Option<Secret<String>>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+pub struct TransactionBankAccountInfo {
+ bank_account: Option<BankAccount>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+pub struct DeutschebankTransactionInfo {
+ back_state: Option<String>,
+ ip_address: Option<Secret<String>>,
+ #[serde(rename = "type")]
+ pm_type: Option<String>,
+ transaction_bankaccount_info: Option<TransactionBankAccountInfo>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct DeutschebankPaymentsResponse {
- status: DeutschebankPaymentStatus,
- id: String,
+ rc: String,
+ message: String,
+ timestamp: String,
+ back_ext_id: Option<String>,
+ back_rc: Option<String>,
+ event_id: Option<String>,
+ kind: Option<String>,
+ tx_action: Option<DeutschebankTXAction>,
+ tx_id: String,
+ amount_total: Option<DeutschebankAmount>,
+ transaction_info: Option<DeutschebankTransactionInfo>,
}
-impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankPaymentsResponse, T, PaymentsResponseData>>
- for RouterData<F, T, PaymentsResponseData>
+impl
+ TryFrom<
+ ResponseRouterData<
+ CompleteAuthorize,
+ DeutschebankPaymentsResponse,
+ CompleteAuthorizeData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: ResponseRouterData<F, DeutschebankPaymentsResponse, T, PaymentsResponseData>,
+ item: ResponseRouterData<
+ CompleteAuthorize,
+ DeutschebankPaymentsResponse,
+ CompleteAuthorizeData,
+ PaymentsResponseData,
+ >,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: common_enums::AttemptStatus::from(item.response.status),
+ status: if item.response.rc == "0" {
+ match item.data.request.is_auto_capture()? {
+ true => common_enums::AttemptStatus::Charged,
+ false => common_enums::AttemptStatus::Authorized,
+ }
+ } else {
+ common_enums::AttemptStatus::Failure
+ },
response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
@@ -144,87 +450,230 @@ impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankPaymentsResponse, T, Paymen
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
-pub struct DeutschebankRefundRequest {
- pub amount: StringMinorUnit,
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum DeutschebankTransactionKind {
+ Directdebit,
}
-impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest {
+#[derive(Debug, Serialize, PartialEq)]
+pub struct DeutschebankCaptureRequest {
+ changed_amount: MinorUnit,
+ kind: DeutschebankTransactionKind,
+}
+
+impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &DeutschebankRouterData<&PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.amount.to_owned(),
+ changed_amount: item.amount,
+ kind: DeutschebankTransactionKind::Directdebit,
})
}
}
-// Type definition for Refund Response
-
-#[allow(dead_code)]
-#[derive(Debug, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+impl
+ TryFrom<
+ ResponseRouterData<
+ Capture,
+ DeutschebankPaymentsResponse,
+ PaymentsCaptureData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ Capture,
+ DeutschebankPaymentsResponse,
+ PaymentsCaptureData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ status: if item.response.rc == "0" {
+ common_enums::AttemptStatus::Charged
+ } else {
+ common_enums::AttemptStatus::Failure
+ },
+ ..item.data
+ })
+ }
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
+impl
+ TryFrom<
+ ResponseRouterData<
+ PSync,
+ DeutschebankPaymentsResponse,
+ PaymentsSyncData,
+ PaymentsResponseData,
+ >,
+ > for RouterData<PSync, PaymentsSyncData, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<
+ PSync,
+ DeutschebankPaymentsResponse,
+ PaymentsSyncData,
+ PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let status = if item.response.rc == "0" {
+ item.response
+ .tx_action
+ .and_then(|tx_action| match tx_action {
+ DeutschebankTXAction::Preauthorization => {
+ Some(common_enums::AttemptStatus::Authorized)
+ }
+ DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => {
+ Some(common_enums::AttemptStatus::Charged)
+ }
+ DeutschebankTXAction::Credit
+ | DeutschebankTXAction::Refund
+ | DeutschebankTXAction::Reversal
+ | DeutschebankTXAction::RiskCheck
+ | DeutschebankTXAction::VerifyMop
+ | DeutschebankTXAction::Payment
+ | DeutschebankTXAction::AccountInformation => None,
+ })
+ } else {
+ Some(common_enums::AttemptStatus::Failure)
+ };
+ match status {
+ Some(status) => Ok(Self {
+ status,
+ ..item.data
+ }),
+ None => Ok(Self { ..item.data }),
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
+#[derive(Debug, Serialize)]
+pub struct DeutschebankReversalRequest {
+ kind: DeutschebankTransactionKind,
+}
+
+impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ kind: DeutschebankTransactionKind::Directdebit,
+ })
+ }
}
-impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>>
+ for PaymentsCancelRouterData
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: RefundsResponseRouterData<Execute, RefundResponse>,
+ item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
+ status: if item.response.rc == "0" {
+ common_enums::AttemptStatus::Voided
+ } else {
+ common_enums::AttemptStatus::VoidFailed
+ },
..item.data
})
}
}
-impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+#[derive(Debug, Serialize)]
+pub struct DeutschebankRefundRequest {
+ changed_amount: MinorUnit,
+ kind: DeutschebankTransactionKind,
+}
+
+impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ changed_amount: item.amount.to_owned(),
+ kind: DeutschebankTransactionKind::Directdebit,
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>>
+ for RefundsRouterData<Execute>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: RefundsResponseRouterData<RSync, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ connector_refund_id: item.response.tx_id,
+ refund_status: if item.response.rc == "0" {
+ enums::RefundStatus::Success
+ } else {
+ enums::RefundStatus::Failure
+ },
}),
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
+impl TryFrom<RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>>
+ for RefundsRouterData<RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let status = if item.response.rc == "0" {
+ item.response
+ .tx_action
+ .and_then(|tx_action| match tx_action {
+ DeutschebankTXAction::Credit | DeutschebankTXAction::Refund => {
+ Some(enums::RefundStatus::Success)
+ }
+ DeutschebankTXAction::Preauthorization
+ | DeutschebankTXAction::Authorization
+ | DeutschebankTXAction::Capture
+ | DeutschebankTXAction::Reversal
+ | DeutschebankTXAction::RiskCheck
+ | DeutschebankTXAction::VerifyMop
+ | DeutschebankTXAction::Payment
+ | DeutschebankTXAction::AccountInformation => None,
+ })
+ } else {
+ Some(enums::RefundStatus::Failure)
+ };
+ match status {
+ Some(refund_status) => Ok(Self {
+ response: Ok(RefundsResponseData {
+ refund_status,
+ connector_refund_id: item.data.request.get_connector_refund_id()?,
+ }),
+ ..item.data
+ }),
+ None => Ok(Self { ..item.data }),
+ }
+ }
+}
+
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DeutschebankErrorResponse {
- pub status_code: u16,
- pub code: String,
+ pub rc: String,
pub message: String,
- pub reason: Option<String>,
}
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 86d6144b1f1..c5ca6512a34 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -7,7 +7,10 @@ pub(crate) mod headers {
pub(crate) const DATE: &str = "Date";
pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key";
pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature";
+ pub(crate) const MERCHANT_ID: &str = "Merchant-ID";
pub(crate) const TIMESTAMP: &str = "Timestamp";
pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version";
pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key";
+ pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue";
+ pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate";
}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 1f50150c08d..b9ae736e435 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -190,7 +190,6 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Bitpay,
- connectors::Deutschebank,
connectors::Fiserv,
connectors::Fiservemea,
connectors::Fiuu,
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index f714dfac86c..b64c745eec0 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -1308,6 +1308,16 @@ pub struct TokenizedBankRedirectValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct TokenizedBankDebitValue2 {
+ pub customer_id: Option<id_type::CustomerId>,
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct TokenizedBankDebitValue1 {
+ pub data: BankDebitData,
+}
+
pub trait GetPaymentMethodType {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType;
}
diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs
index d27c7974092..3d47afb9b82 100644
--- a/crates/hyperswitch_domain_models/src/types.rs
+++ b/crates/hyperswitch_domain_models/src/types.rs
@@ -1,13 +1,14 @@
use crate::{
- router_data::RouterData,
+ router_data::{AccessToken, RouterData},
router_flow_types::{
- Authorize, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, PSync,
- PaymentMethodToken, RSync, SetupMandate, Void,
+ AccessTokenAuth, Authorize, CalculateTax, Capture, CompleteAuthorize,
+ CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, Void,
},
router_request_types::{
- CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData,
- PaymentsTaxCalculationData, RefundsData, SetupMandateRequestData,
+ AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData,
+ PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
+ PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData,
+ SetupMandateRequestData,
},
router_response_types::{
PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData,
@@ -31,3 +32,4 @@ pub type PaymentsCompleteAuthorizeRouterData =
RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
pub type PaymentsTaxCalculationRouterData =
RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
+pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index acffafa6c32..659c94423d4 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -11209,8 +11209,43 @@ impl Default for super::settings::RequiredFields {
}
)
]),
- })
- ]),
+ }
+ ),
+ (
+ enums::Connector::Deutschebank,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from([ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.first_name".to_string(),
+ display_name: "owner_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.billing.address.last_name".to_string(),
+ display_name: "owner_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.bank_debit.sepa.iban".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.bank_debit.bacs.iban".to_string(),
+ display_name: "bank_account_number".to_string(),
+ field_type: enums::FieldType::Text,
+ value: None,
+ }
+ )
+ ]),
+ }
+ )
+ ]),
},
),
(
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 996224d7bea..75b8d922f82 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1300,6 +1300,10 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?;
Ok(())
}
+ api_enums::Connector::Deutschebank => {
+ deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Dlocal => {
dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 0061eb4fbc0..9a39a3c341b 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -79,9 +79,22 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
+ pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => {
+ let payment_token = helpers::store_payment_method_data_in_vault(
+ state,
+ payment_attempt,
+ payment_intent,
+ enums::PaymentMethod::BankDebit,
+ pm,
+ merchant_key_store,
+ business_profile,
+ )
+ .await?;
+
+ Ok((pm_opt.to_owned(), payment_token))
+ }
pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
- pm @ Some(domain::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 54da4308bfb..75278010ceb 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -279,6 +279,58 @@ impl Vaultable for domain::BankRedirectData {
}
}
+impl Vaultable for domain::BankDebitData {
+ fn get_value1(
+ &self,
+ _customer_id: Option<id_type::CustomerId>,
+ ) -> CustomResult<String, errors::VaultError> {
+ let value1 = domain::TokenizedBankDebitValue1 {
+ data: self.to_owned(),
+ };
+
+ value1
+ .encode_to_string_of_json()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode bank debit data")
+ }
+
+ fn get_value2(
+ &self,
+ customer_id: Option<id_type::CustomerId>,
+ ) -> CustomResult<String, errors::VaultError> {
+ let value2 = domain::TokenizedBankDebitValue2 { customer_id };
+
+ value2
+ .encode_to_string_of_json()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode bank debit supplementary data")
+ }
+
+ fn from_values(
+ value1: String,
+ value2: String,
+ ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> {
+ let value1: domain::TokenizedBankDebitValue1 = value1
+ .parse_struct("TokenizedBankDebitValue1")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Could not deserialize into bank debit data")?;
+
+ let value2: domain::TokenizedBankDebitValue2 = value2
+ .parse_struct("TokenizedBankDebitValue2")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Could not deserialize into supplementary bank debit data")?;
+
+ let bank_transfer_data = value1.data;
+
+ let supp_data = SupplementaryVaultData {
+ customer_id: value2.customer_id,
+ payment_method_id: None,
+ };
+
+ Ok((bank_transfer_data, supp_data))
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum VaultPaymentMethod {
@@ -286,6 +338,7 @@ pub enum VaultPaymentMethod {
Wallet(String),
BankTransfer(String),
BankRedirect(String),
+ BankDebit(String),
}
impl Vaultable for domain::PaymentMethodData {
@@ -302,6 +355,9 @@ impl Vaultable for domain::PaymentMethodData {
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?)
}
+ Self::BankDebit(bank_debit) => {
+ VaultPaymentMethod::BankDebit(bank_debit.get_value1(customer_id)?)
+ }
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
@@ -325,6 +381,9 @@ impl Vaultable for domain::PaymentMethodData {
Self::BankRedirect(bank_redirect) => {
VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?)
}
+ Self::BankDebit(bank_debit) => {
+ VaultPaymentMethod::BankDebit(bank_debit.get_value2(customer_id)?)
+ }
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported")?,
};
@@ -374,6 +433,10 @@ impl Vaultable for domain::PaymentMethodData {
domain::BankRedirectData::from_values(mvalue1, mvalue2)?;
Ok((Self::BankRedirect(bank_redirect), supp_data))
}
+ (VaultPaymentMethod::BankDebit(mvalue1), VaultPaymentMethod::BankDebit(mvalue2)) => {
+ let (bank_debit, supp_data) = domain::BankDebitData::from_values(mvalue1, mvalue2)?;
+ Ok((Self::BankDebit(bank_debit), supp_data))
+ }
_ => Err(errors::VaultError::PaymentMethodNotSupported)
.attach_printable("Payment method not supported"),
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 5f9c1a7be0b..6cb4532d617 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1770,6 +1770,10 @@ pub async fn retrieve_payment_method_with_temporary_token(
Some((the_pm, enums::PaymentMethod::BankRedirect))
}
+ Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => {
+ Some((the_pm, enums::PaymentMethod::BankDebit))
+ }
+
Some(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method received from locker is unsupported by locker")?,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index ca86003f4b4..34dea537b2d 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -359,9 +359,9 @@ impl ConnectorData {
enums::Connector::Datatrans => {
Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new())))
}
- // enums::Connector::Deutschebank => {
- // Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
- // }
+ enums::Connector::Deutschebank => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new())))
+ }
enums::Connector::Dlocal => Ok(ConnectorEnum::Old(Box::new(&connector::Dlocal))),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new(
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 1cf36bc4428..bfd7b54f556 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -6,8 +6,9 @@ pub use hyperswitch_domain_models::payment_method_data::{
GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData,
KakaoPayRedirection, MbWayRedirection, MifinityData, OpenBankingData, PayLaterData,
PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, SepaAndBacsBillingDetails,
- SwishQrData, TokenizedBankRedirectValue1, TokenizedBankRedirectValue2,
- TokenizedBankTransferValue1, TokenizedBankTransferValue2, TokenizedCardValue1,
- TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, TouchNGoRedirection,
- UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr,
+ SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2, TokenizedBankRedirectValue1,
+ TokenizedBankRedirectValue2, TokenizedBankTransferValue1, TokenizedBankTransferValue2,
+ TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData,
+ WeChatPayQr,
};
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index f883d1d4c50..46210d4dd09 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -274,7 +274,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Cryptopay => Self::Cryptopay,
api_enums::Connector::Cybersource => Self::Cybersource,
api_enums::Connector::Datatrans => Self::Datatrans,
- // api_enums::Connector::Deutschebank => Self::Deutschebank,
+ api_enums::Connector::Deutschebank => Self::Deutschebank,
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Fiserv => Self::Fiserv,
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 6ed9bd7103d..f61770a5bde 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -276,7 +276,9 @@ api_key = "API Key"
api_key="API Key"
[deutschebank]
-api_key="API Key"
+api_key = "Client ID"
+key1 = "Merchant ID"
+api_secret = "Client Key"
[thunes]
-api_key="API Key"
\ No newline at end of file
+api_key="API Key"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 68895e5876e..a0fed3c003a 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -31,7 +31,7 @@ pub struct ConnectorAuthentication {
pub cryptopay: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
pub datatrans: Option<HeaderKey>,
- pub deutschebank: Option<HeaderKey>,
+ pub deutschebank: Option<SignatureKey>,
pub dlocal: Option<SignatureKey>,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index b1f74f57feb..ed15e8893bd 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -96,7 +96,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
datatrans.base_url = "https://api.sandbox.datatrans.com/"
-deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1"
+deutschebank.base_url = "https://testmerch.directpos.de/rest-api"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
| 2024-09-06T10:29:05Z |
## Description
<!-- Describe your changes in detail -->
Integrate SEPA Payments for connector Deutsche Bank
https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html#chap_sdd
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/5858
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Authorize:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 9000,
"currency": "EUR",
"confirm": true,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87123456781234567890"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
}'
```
Response:
```
{
"payment_id": "pay_9SIimBI1UXiGdsR4XCmH",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 9000,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_9SIimBI1UXiGdsR4XCmH_secret_s0dXk9MNEsKru7clJoNK",
"created": "2024-09-12T10:41:39.816Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_IORpLx2lNN9VK64COwy0",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://example.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_9SIimBI1UXiGdsR4XCmH/merchant_1725539597/pay_9SIimBI1UXiGdsR4XCmH_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726137699,
"expires": 1726141299,
"secret": "epk_a677e949924b417cb73e1badf1ac05f8"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:56:39.816Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:41:42.563Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Then do redirection
2. PSYNC:
Request:
```
curl --location 'http://localhost:8080/payments/pay_aCYBEjtBmw7l7u4jQWhM' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb'
```
Response:
```
{
"payment_id": "pay_aCYBEjtBmw7l7u4jQWhM",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": 9000,
"connector": "deutschebank",
"client_secret": "pay_aCYBEjtBmw7l7u4jQWhM_secret_4TLRv0W2zGPEaN5hxwOC",
"created": "2024-09-12T10:32:33.053Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_1gP6ixqxxYORXgW6mAxq",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "fNo3C3goIky4BNzSU7ys9n",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:47:33.053Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:40:37.356Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_zwqrtx6EMgaV2gkK7WdS/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{}'
```
Response:
```
{
"payment_id": "pay_zwqrtx6EMgaV2gkK7WdS",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": 9000,
"connector": "deutschebank",
"client_secret": "pay_zwqrtx6EMgaV2gkK7WdS_secret_Br19bUUvGCMLAiG1Fusv",
"created": "2024-09-12T10:42:41.662Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_RzJMp7J8sp2wWoRnBYPA",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "8v739jbpsaKxnsCB52QmeF",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:57:41.662Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:42:57.446Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
4. Void:
Request:
```
curl --location 'http://localhost:8080/payments/pay_sH3vFdwGOoPjobg4sud9/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{}'
```
Response:
```
{
"payment_id": "pay_sH3vFdwGOoPjobg4sud9",
"merchant_id": "merchant_1725539597",
"status": "cancelled",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_sH3vFdwGOoPjobg4sud9_secret_jlUGjGn6ADDu02Ql8O4K",
"created": "2024-09-12T10:44:13.912Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_2Mq0WwprhovjSGXcJmZa",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "9VFMneA8NhYUj7xoG0bmMA",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:59:13.912Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:44:39.083Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
5. Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"refund_type": "instant"
}'
```
Response:
```
{
"refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ",
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"amount": 9000,
"currency": "EUR",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-09-16T07:57:15.637Z",
"updated_at": "2024-09-16T07:57:18.072Z",
"connector": "deutschebank",
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"charges": null
}
```
6. RSYNC:
Request:
```
curl --location 'http://localhost:8080/refunds/ref_UDEk9Xks0pRZI5GdY1BJ' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb'
```
Response:
```
{
"refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ",
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"amount": 9000,
"currency": "EUR",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-09-16T07:57:15.637Z",
"updated_at": "2024-09-16T07:58:34.252Z",
"connector": "deutschebank",
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"charges": null
}
``` | 10ac08944986a1fd101f8f05263e92ed7ebbba94 |
1. Authorize:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"amount": 9000,
"currency": "EUR",
"confirm": true,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"customer_id": "customer123",
"payment_method": "bank_debit",
"payment_method_type": "sepa",
"payment_method_data": {
"bank_debit": {
"sepa_bank_debit": {
"iban": "DE87123456781234567890"
}
}
},
"billing": {
"address": {
"first_name": "joseph",
"last_name": "Doe"
}
},
}'
```
Response:
```
{
"payment_id": "pay_9SIimBI1UXiGdsR4XCmH",
"merchant_id": "merchant_1725539597",
"status": "requires_customer_action",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 9000,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_9SIimBI1UXiGdsR4XCmH_secret_s0dXk9MNEsKru7clJoNK",
"created": "2024-09-12T10:41:39.816Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_IORpLx2lNN9VK64COwy0",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://example.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_9SIimBI1UXiGdsR4XCmH/merchant_1725539597/pay_9SIimBI1UXiGdsR4XCmH_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "customer123",
"created_at": 1726137699,
"expires": 1726141299,
"secret": "epk_a677e949924b417cb73e1badf1ac05f8"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:56:39.816Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:41:42.563Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Then do redirection
2. PSYNC:
Request:
```
curl --location 'http://localhost:8080/payments/pay_aCYBEjtBmw7l7u4jQWhM' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb'
```
Response:
```
{
"payment_id": "pay_aCYBEjtBmw7l7u4jQWhM",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": 9000,
"connector": "deutschebank",
"client_secret": "pay_aCYBEjtBmw7l7u4jQWhM_secret_4TLRv0W2zGPEaN5hxwOC",
"created": "2024-09-12T10:32:33.053Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_1gP6ixqxxYORXgW6mAxq",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "fNo3C3goIky4BNzSU7ys9n",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:47:33.053Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:40:37.356Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
3. Capture:
Request:
```
curl --location 'http://localhost:8080/payments/pay_zwqrtx6EMgaV2gkK7WdS/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{}'
```
Response:
```
{
"payment_id": "pay_zwqrtx6EMgaV2gkK7WdS",
"merchant_id": "merchant_1725539597",
"status": "succeeded",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": 9000,
"connector": "deutschebank",
"client_secret": "pay_zwqrtx6EMgaV2gkK7WdS_secret_Br19bUUvGCMLAiG1Fusv",
"created": "2024-09-12T10:42:41.662Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_RzJMp7J8sp2wWoRnBYPA",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "8v739jbpsaKxnsCB52QmeF",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:57:41.662Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:42:57.446Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
4. Void:
Request:
```
curl --location 'http://localhost:8080/payments/pay_sH3vFdwGOoPjobg4sud9/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{}'
```
Response:
```
{
"payment_id": "pay_sH3vFdwGOoPjobg4sud9",
"merchant_id": "merchant_1725539597",
"status": "cancelled",
"amount": 9000,
"net_amount": 9000,
"amount_capturable": 0,
"amount_received": null,
"connector": "deutschebank",
"client_secret": "pay_sH3vFdwGOoPjobg4sud9_secret_jlUGjGn6ADDu02Ql8O4K",
"created": "2024-09-12T10:44:13.912Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "bank_debit",
"payment_method_data": {
"bank_debit": {
"sepa": {
"iban": "DE871************67890",
"bank_account_holder_name": null
}
},
"billing": null
},
"payment_token": "token_2Mq0WwprhovjSGXcJmZa",
"shipping": null,
"billing": {
"address": {
"city": null,
"country": null,
"line1": null,
"line2": null,
"line3": null,
"zip": null,
"state": null,
"first_name": "joseph",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "sepa",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "9VFMneA8NhYUj7xoG0bmMA",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-09-12T10:59:13.912Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-09-12T10:44:39.083Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
5. Refunds:
Request:
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \
--data '{
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"refund_type": "instant"
}'
```
Response:
```
{
"refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ",
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"amount": 9000,
"currency": "EUR",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-09-16T07:57:15.637Z",
"updated_at": "2024-09-16T07:57:18.072Z",
"connector": "deutschebank",
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"charges": null
}
```
6. RSYNC:
Request:
```
curl --location 'http://localhost:8080/refunds/ref_UDEk9Xks0pRZI5GdY1BJ' \
--header 'Accept: application/json' \
--header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb'
```
Response:
```
{
"refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ",
"payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv",
"amount": 9000,
"currency": "EUR",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-09-16T07:57:15.637Z",
"updated_at": "2024-09-16T07:58:34.252Z",
"connector": "deutschebank",
"profile_id": "pro_EuXuxP2KVO0m1tlDWSau",
"merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2",
"charges": null
}
```
| [
"api-reference-v2/openapi_spec.json",
"config/config.example.toml",
"config/deployments/integration_test.toml",
"config/deployments/production.toml",
"config/deployments/sandbox.toml",
"config/development.toml",
"config/docker_compose.toml",
"crates/api_models/src/enums.rs",
"crates/common_enums/src... | |
juspay/hyperswitch | juspay__hyperswitch-5822 | Bug: feat(analytics): Revert api_event metrics and filters back to merchant_id authentication
`api_event_metrics` and `api_event_filters` APIs were modified to authenticate through AuthInfo where there are MerchantLevel, ProfileLevel and OrgLevel authentication. (https://github.com/juspay/hyperswitch/pull/5729)
But ApiEvents table is not yet populated with organization_id and profile_id, hence should be reverted back. | diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs
index f3a7b154b90..305de7e69c8 100644
--- a/crates/analytics/src/api_event/core.rs
+++ b/crates/analytics/src/api_event/core.rs
@@ -21,7 +21,6 @@ use super::{
metrics::ApiEventMetricRow,
};
use crate::{
- enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
types::FiltersError,
@@ -52,7 +51,7 @@ pub async fn api_events_core(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetApiEventFiltersRequest,
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<ApiEventFiltersResponse> {
use api_models::analytics::{api_event::ApiEventDimensions, ApiEventFilterValue};
@@ -69,7 +68,8 @@ pub async fn get_filters(
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
- get_api_event_filter_for_dimension(dim, auth, &req.time_range, ckh_pool).await
+ get_api_event_filter_for_dimension(dim, merchant_id, &req.time_range, ckh_pool)
+ .await
}
}
.switch()?
@@ -92,7 +92,7 @@ pub async fn get_filters(
#[instrument(skip_all)]
pub async fn get_api_event_metrics(
pool: &AnalyticsProvider,
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetApiEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<ApiEventMetricsBucketIdentifier, ApiEventMetricRow> =
@@ -109,14 +109,14 @@ pub async fn get_api_event_metrics(
// TODO: lifetime issues with joinset,
// can be optimized away if joinset lifetime requirements are relaxed
- let auth_scoped = auth.to_owned();
+ let merchant_id_scoped = merchant_id.to_owned();
set.spawn(
async move {
let data = pool
.get_api_event_metrics(
&metric_type,
&req.group_by_names.clone(),
- &auth_scoped,
+ &merchant_id_scoped,
&req.filters,
&req.time_series.map(|t| t.granularity),
&req.time_range,
diff --git a/crates/analytics/src/api_event/filters.rs b/crates/analytics/src/api_event/filters.rs
index 5c8136805c9..62fd8789018 100644
--- a/crates/analytics/src/api_event/filters.rs
+++ b/crates/analytics/src/api_event/filters.rs
@@ -4,7 +4,6 @@ use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
- enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow},
};
@@ -13,7 +12,7 @@ pub trait ApiEventFilterAnalytics: LoadRow<ApiEventFilter> {}
pub async fn get_api_event_filter_for_dimension<T>(
dimension: ApiEventDimensions,
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<ApiEventFilter>>
@@ -33,7 +32,9 @@ where
.attach_printable("Error filtering time range")
.switch()?;
- auth.set_filter_clause(&mut query_builder).switch()?;
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
query_builder.set_distinct();
diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs
index 48e95b6b5cd..ac29ec15169 100644
--- a/crates/analytics/src/api_event/metrics.rs
+++ b/crates/analytics/src/api_event/metrics.rs
@@ -7,7 +7,6 @@ use api_models::analytics::{
use time::PrimitiveDateTime;
use crate::{
- enums::AuthInfo,
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult},
};
@@ -44,7 +43,7 @@ where
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -65,7 +64,7 @@ where
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -74,17 +73,38 @@ where
match self {
Self::Latency => {
MaxLatency
- .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
.await
}
Self::ApiCount => {
ApiCount
- .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
.await
}
Self::StatusCodeCount => {
StatusCodeCount
- .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
.await
}
}
diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs
index 3973870a455..f00c01bbf38 100644
--- a/crates/analytics/src/api_event/metrics/api_count.rs
+++ b/crates/analytics/src/api_event/metrics/api_count.rs
@@ -10,7 +10,6 @@ use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
- enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
@@ -31,7 +30,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -70,7 +69,9 @@ where
.switch()?;
}
- auth.set_filter_clause(&mut query_builder).switch()?;
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
time_range
.set_filter_clause(&mut query_builder)
diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs
index c9a62abe676..5d71da2a0aa 100644
--- a/crates/analytics/src/api_event/metrics/latency.rs
+++ b/crates/analytics/src/api_event/metrics/latency.rs
@@ -10,7 +10,6 @@ use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
- enums::AuthInfo,
query::{
Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
Window,
@@ -34,7 +33,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -77,7 +76,9 @@ where
filters.set_filter_clause(&mut query_builder).switch()?;
- auth.set_filter_clause(&mut query_builder).switch()?;
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
time_range
.set_filter_clause(&mut query_builder)
diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs
index 190f38999c9..b4fff367b62 100644
--- a/crates/analytics/src/api_event/metrics/status_code_count.rs
+++ b/crates/analytics/src/api_event/metrics/status_code_count.rs
@@ -10,7 +10,6 @@ use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
- enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
@@ -31,7 +30,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -48,7 +47,9 @@ where
filters.set_filter_clause(&mut query_builder).switch()?;
- auth.set_filter_clause(&mut query_builder).switch()?;
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
time_range
.set_filter_clause(&mut query_builder)
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 66005a61b75..d5cb3c718df 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -828,7 +828,7 @@ impl AnalyticsProvider {
&self,
metric: &ApiEventMetrics,
dimensions: &[ApiEventDimensions],
- auth: &AuthInfo,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -840,7 +840,14 @@ impl AnalyticsProvider {
| Self::CombinedSqlx(_, ckh_pool) => {
// Since API events are ckh only use ckh here
metric
- .load_metrics(dimensions, auth, filters, granularity, time_range, ckh_pool)
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ )
.await
}
}
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 7c4d1acc6bf..879db9a5a67 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -215,14 +215,6 @@ pub mod routes {
web::resource("filters/disputes")
.route(web::post().to(get_org_dispute_filters)),
)
- .service(
- web::resource("filters/api_events")
- .route(web::post().to(get_org_api_event_filters)),
- )
- .service(
- web::resource("metrics/api_events")
- .route(web::post().to(get_org_api_events_metrics)),
- )
.service(
web::resource("report/dispute")
.route(web::post().to(generate_org_dispute_report)),
@@ -257,14 +249,6 @@ pub mod routes {
web::resource("filters/refunds")
.route(web::post().to(get_profile_refund_filters)),
)
- .service(
- web::resource("metrics/api_events")
- .route(web::post().to(get_profile_api_events_metrics)),
- )
- .service(
- web::resource("filters/api_events")
- .route(web::post().to(get_profile_api_event_filters)),
- )
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_profile_dispute_metrics)),
@@ -1757,100 +1741,13 @@ pub mod routes {
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let merchant_id = auth.merchant_account.get_id();
- let auth: AuthInfo = AuthInfo::MerchantLevel {
- org_id: org_id.clone(),
- merchant_ids: vec![merchant_id.clone()],
- };
- analytics::api_event::get_api_event_metrics(&state.pool, &auth, req)
- .await
- .map(ApplicationResponse::Json)
- },
- &auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
-
- /// # Panics
- ///
- /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
- pub async fn get_org_api_events_metrics(
- state: web::Data<AppState>,
- req: actix_web::HttpRequest,
- json_payload: web::Json<[GetApiEventMetricRequest; 1]>,
- ) -> impl Responder {
- // safety: This shouldn't panic owing to the data type
- #[allow(clippy::expect_used)]
- let payload = json_payload
- .into_inner()
- .to_vec()
- .pop()
- .expect("Couldn't get GetApiEventMetricRequest");
- let flow = AnalyticsFlow::GetApiEventMetrics;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let auth: AuthInfo = AuthInfo::OrgLevel {
- org_id: org_id.clone(),
- };
- analytics::api_event::get_api_event_metrics(&state.pool, &auth, req)
- .await
- .map(ApplicationResponse::Json)
- },
- &auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
-
- /// # Panics
- ///
- /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element.
- pub async fn get_profile_api_events_metrics(
- state: web::Data<AppState>,
- req: actix_web::HttpRequest,
- json_payload: web::Json<[GetApiEventMetricRequest; 1]>,
- ) -> impl Responder {
- // safety: This shouldn't panic owing to the data type
- #[allow(clippy::expect_used)]
- let payload = json_payload
- .into_inner()
- .to_vec()
- .pop()
- .expect("Couldn't get GetApiEventMetricRequest");
- let flow = AnalyticsFlow::GetApiEventMetrics;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let merchant_id = auth.merchant_account.get_id();
- let profile_id = auth
- .profile_id
- .ok_or(report!(UserErrors::JwtProfileIdMissing))
- .change_context(AnalyticsError::AccessForbiddenError)?;
- let auth: AuthInfo = AuthInfo::ProfileLevel {
- org_id: org_id.clone(),
- merchant_id: merchant_id.clone(),
- profile_ids: vec![profile_id.clone()],
- };
- analytics::api_event::get_api_event_metrics(&state.pool, &auth, req)
- .await
- .map(ApplicationResponse::Json)
+ analytics::api_event::get_api_event_metrics(
+ &state.pool,
+ auth.merchant_account.get_id(),
+ req,
+ )
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::Analytics,
@@ -1873,78 +1770,7 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let merchant_id = auth.merchant_account.get_id();
- let auth: AuthInfo = AuthInfo::MerchantLevel {
- org_id: org_id.clone(),
- merchant_ids: vec![merchant_id.clone()],
- };
- analytics::api_event::get_filters(&state.pool, req, &auth)
- .await
- .map(ApplicationResponse::Json)
- },
- &auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
-
- pub async fn get_org_api_event_filters(
- state: web::Data<AppState>,
- req: actix_web::HttpRequest,
- json_payload: web::Json<GetApiEventFiltersRequest>,
- ) -> impl Responder {
- let flow = AnalyticsFlow::GetApiEventFilters;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- json_payload.into_inner(),
- |state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let auth: AuthInfo = AuthInfo::OrgLevel {
- org_id: org_id.clone(),
- };
- analytics::api_event::get_filters(&state.pool, req, &auth)
- .await
- .map(ApplicationResponse::Json)
- },
- &auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
- }
-
- pub async fn get_profile_api_event_filters(
- state: web::Data<AppState>,
- req: actix_web::HttpRequest,
- json_payload: web::Json<GetApiEventFiltersRequest>,
- ) -> impl Responder {
- let flow = AnalyticsFlow::GetApiEventFilters;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- json_payload.into_inner(),
- |state, auth: AuthenticationData, req, _| async move {
- let org_id = auth.merchant_account.get_org_id();
- let merchant_id = auth.merchant_account.get_id();
- let profile_id = auth
- .profile_id
- .ok_or(report!(UserErrors::JwtProfileIdMissing))
- .change_context(AnalyticsError::AccessForbiddenError)?;
- let auth: AuthInfo = AuthInfo::ProfileLevel {
- org_id: org_id.clone(),
- merchant_id: merchant_id.clone(),
- profile_ids: vec![profile_id.clone()],
- };
- analytics::api_event::get_filters(&state.pool, req, &auth)
+ analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
| 2024-09-06T05:59:52Z |
## Description
<!-- Describe your changes in detail -->
Previously modified api_event_metrics and api_event_filters to authenticate through AuthInfo where there are MerchantLevel, ProfileLevel and OrgLevel authentication. ([https://github.com/juspay/hyperswitch/pull/5729](https://github.com/juspay/hyperswitch/pull/5729))
But ApiEvents table is not populated with `organization_id` and `profile_id`, hence reverting back.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Fix the issues on sandbox analytics related to api_events.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Spoke with dashboard team and removed the following api endpoints:
- /analytics/v1/profile/metrics/api_events
- /analytics/v1/profile/filters/api_events
- /analytics/v1/org/metrics/api_events
- /analytics/v1/org/filters/api_events | d3a1703bf59afc06e87e94433bc10a01e413259b |
Spoke with dashboard team and removed the following api endpoints:
- /analytics/v1/profile/metrics/api_events
- /analytics/v1/profile/filters/api_events
- /analytics/v1/org/metrics/api_events
- /analytics/v1/org/filters/api_events
| [
"crates/analytics/src/api_event/core.rs",
"crates/analytics/src/api_event/filters.rs",
"crates/analytics/src/api_event/metrics.rs",
"crates/analytics/src/api_event/metrics/api_count.rs",
"crates/analytics/src/api_event/metrics/latency.rs",
"crates/analytics/src/api_event/metrics/status_code_count.rs",
"... | |
juspay/hyperswitch | juspay__hyperswitch-5820 | Bug: feat(users): Add profile level role and profile level authz
- Create profile level users.
- Create authorization checks for entity level in apis. default to merchant | diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index a6e94ed294a..7c4d1acc6bf 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -20,6 +20,7 @@ pub mod routes {
GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest,
GetSdkEventMetricRequest, ReportRequest,
};
+ use common_enums::EntityType;
use error_stack::{report, ResultExt};
use crate::{
@@ -393,7 +394,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -429,7 +433,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -472,7 +479,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -510,7 +520,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -546,7 +559,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -589,7 +605,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -627,7 +646,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -663,7 +685,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -706,7 +731,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -738,7 +766,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -774,7 +805,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -811,7 +845,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -848,7 +885,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -876,7 +916,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -902,7 +945,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -935,7 +981,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -961,7 +1010,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -989,7 +1041,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1015,7 +1070,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1048,7 +1106,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1070,7 +1131,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1096,7 +1160,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1126,7 +1193,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1157,7 +1227,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1186,7 +1259,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1234,7 +1310,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1280,7 +1359,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Organization,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1333,7 +1415,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1381,7 +1466,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1427,7 +1515,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Organization,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1480,7 +1571,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1528,7 +1622,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1574,7 +1671,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Organization,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1626,7 +1726,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::GenerateReport),
+ &auth::JWTAuth {
+ permission: Permission::GenerateReport,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1664,7 +1767,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1700,7 +1806,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1743,7 +1852,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1771,7 +1883,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1797,7 +1912,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1830,7 +1948,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1859,7 +1980,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1899,7 +2023,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1939,7 +2066,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1967,7 +2097,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -2000,7 +2133,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -2026,7 +2162,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -2064,7 +2203,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -2107,7 +2249,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -2143,7 +2288,10 @@ pub mod routes {
.await
.map(ApplicationResponse::Json)
},
- &auth::JWTAuth(Permission::Analytics),
+ &auth::JWTAuth {
+ permission: Permission::Analytics,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index d7afe8dafde..3f315360211 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -90,7 +90,7 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_";
-pub const ROLE_CACHE_PREFIX: &str = "CR_";
+pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs
index 672e5830013..fbabec67291 100644
--- a/crates/router/src/consts/user_role.rs
+++ b/crates/router/src/consts/user_role.rs
@@ -5,5 +5,6 @@ pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin";
pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer";
pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator";
pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support";
+pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support";
pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000";
pub const MAX_ROLE_NAME_LENGTH: usize = 64;
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index ae97bfe6044..ae92360b13e 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -118,6 +119,7 @@ pub async fn retrieve_merchant_account(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -170,6 +172,7 @@ pub async fn update_merchant_account(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -230,6 +233,7 @@ pub async fn connector_create(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -261,6 +265,7 @@ pub async fn connector_create(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -323,6 +328,7 @@ pub async fn connector_retrieve(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -361,6 +367,7 @@ pub async fn connector_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorAccountRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -406,6 +413,7 @@ pub async fn payment_connector_list(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -457,6 +465,7 @@ pub async fn payment_connector_list_profile(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -517,6 +526,7 @@ pub async fn connector_update(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -568,6 +578,7 @@ pub async fn connector_update(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -623,6 +634,7 @@ pub async fn connector_delete(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -661,6 +673,7 @@ pub async fn connector_delete(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -743,6 +756,7 @@ pub async fn business_profile_create(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -773,6 +787,7 @@ pub async fn business_profile_create(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -807,6 +822,7 @@ pub async fn business_profile_retrieve(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -837,6 +853,7 @@ pub async fn business_profile_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -872,6 +889,7 @@ pub async fn business_profile_update(
&auth::JWTAuthMerchantAndProfileFromRoute {
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
+ minimum_entity_level: EntityType::Merchant,
required_permission: Permission::MerchantAccountWrite,
},
req.headers(),
@@ -904,6 +922,7 @@ pub async fn business_profile_update(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -955,6 +974,7 @@ pub async fn business_profiles_list(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -989,6 +1009,7 @@ pub async fn business_profiles_list_at_profile_level(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -1018,7 +1039,10 @@ pub async fn toggle_connector_agnostic_mit(
|state, _, req, _| connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 68e5687e249..71632cc5749 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, Responder};
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -37,6 +38,7 @@ pub async fn api_key_create(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -67,6 +69,7 @@ pub async fn api_key_create(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -104,6 +107,7 @@ pub async fn api_key_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::ApiKeyRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -136,6 +140,7 @@ pub async fn api_key_retrieve(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ApiKeyRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -172,6 +177,7 @@ pub async fn api_key_update(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -204,6 +210,7 @@ pub async fn api_key_update(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -237,6 +244,7 @@ pub async fn api_key_revoke(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -266,6 +274,7 @@ pub async fn api_key_revoke(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::ApiKeyWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -318,6 +327,7 @@ pub async fn api_key_list(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::ApiKeyRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index f2a70a7b905..4738df5ed2c 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -1,5 +1,6 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
+use common_enums::EntityType;
use router_env::Flow;
use crate::{
@@ -36,7 +37,10 @@ pub async fn add_entry_to_blocklist(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -72,7 +76,10 @@ pub async fn remove_entry_from_blocklist(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -110,7 +117,10 @@ pub async fn list_blocked_payment_methods(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountRead),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -148,7 +158,10 @@ pub async fn toggle_blocklist_guard(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs
index f5555f5bf9b..f7494e182c1 100644
--- a/crates/router/src/routes/connector_onboarding.rs
+++ b/crates/router/src/routes/connector_onboarding.rs
@@ -1,5 +1,6 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::connector_onboarding as api_types;
+use common_enums::EntityType;
use router_env::Flow;
use super::AppState;
@@ -21,7 +22,10 @@ pub async fn get_action_url(
&http_req,
req_payload.clone(),
core::get_action_url,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -40,7 +44,10 @@ pub async fn sync_onboarding_status(
&http_req,
req_payload.clone(),
core::sync_onboarding_status,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -59,7 +66,10 @@ pub async fn reset_tracking_id(
&http_req,
req_payload.clone(),
core::reset_tracking_id,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 2e3ce35a974..66ff1f8e323 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse, Responder};
+use common_enums::EntityType;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
@@ -25,7 +26,10 @@ pub async fn customers_create(
|state, auth, req, _| create_customer(state, auth.merchant_account, auth.key_store, req),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::CustomerWrite),
+ &auth::JWTAuth {
+ permission: Permission::CustomerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -48,7 +52,10 @@ pub async fn customers_retrieve(
.into_inner();
let auth = if auth::is_jwt_auth(req.headers()) {
- Box::new(auth::JWTAuth(Permission::CustomerRead))
+ Box::new(auth::JWTAuth {
+ permission: Permission::CustomerRead,
+ minimum_entity_level: EntityType::Merchant,
+ })
} else {
match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
@@ -88,7 +95,10 @@ pub async fn customers_retrieve(
let payload = web::Json(customers::GlobalId::new(path.into_inner())).into_inner();
let auth = if auth::is_jwt_auth(req.headers()) {
- Box::new(auth::JWTAuth(Permission::CustomerRead))
+ Box::new(auth::JWTAuth {
+ permission: Permission::CustomerRead,
+ minimum_entity_level: EntityType::Merchant,
+ })
} else {
match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
@@ -133,7 +143,10 @@ pub async fn customers_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::CustomerRead),
+ &auth::JWTAuth {
+ permission: Permission::CustomerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -169,7 +182,10 @@ pub async fn customers_update(
},
auth::auth_type(
&auth::ApiKeyAuth,
- &auth::JWTAuth(Permission::CustomerWrite),
+ &auth::JWTAuth {
+ permission: Permission::CustomerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -204,7 +220,10 @@ pub async fn customers_update(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::CustomerWrite),
+ &auth::JWTAuth {
+ permission: Permission::CustomerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -230,7 +249,10 @@ pub async fn customers_delete(
|state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::CustomerWrite),
+ &auth::JWTAuth {
+ permission: Permission::CustomerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -259,7 +281,10 @@ pub async fn customers_delete(
|state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::CustomerWrite),
+ &auth::JWTAuth {
+ permission: Permission::CustomerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -294,7 +319,10 @@ pub async fn get_customer_mandates(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MandateRead),
+ &auth::JWTAuth {
+ permission: Permission::MandateRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index e8edcd704d7..98ba33a64b4 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -1,6 +1,7 @@
use actix_multipart::Multipart;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::disputes as dispute_models;
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use crate::{core::api_locking, services::authorization::permissions::Permission};
@@ -48,7 +49,10 @@ pub async fn retrieve_dispute(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeRead),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -97,7 +101,10 @@ pub async fn retrieve_disputes_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeRead),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -152,7 +159,10 @@ pub async fn retrieve_disputes_list_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeRead),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -201,7 +211,10 @@ pub async fn accept_dispute(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeWrite),
+ &auth::JWTAuth {
+ permission: Permission::DisputeWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -244,7 +257,10 @@ pub async fn submit_dispute_evidence(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeWrite),
+ &auth::JWTAuth {
+ permission: Permission::DisputeWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -295,7 +311,10 @@ pub async fn attach_dispute_evidence(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeWrite),
+ &auth::JWTAuth {
+ permission: Permission::DisputeWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -338,7 +357,10 @@ pub async fn retrieve_dispute_evidence(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeRead),
+ &auth::JWTAuth {
+ permission: Permission::DisputeRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -376,7 +398,10 @@ pub async fn delete_dispute_evidence(
|state, auth, req, _| disputes::delete_evidence(state, auth.merchant_account, req),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::DisputeWrite),
+ &auth::JWTAuth {
+ permission: Permission::DisputeWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index d2c5d5e4644..70b36f87983 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -131,7 +132,10 @@ pub async fn retrieve_mandates_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MandateRead),
+ &auth::JWTAuth {
+ permission: Permission::MandateRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index b3c7f5cc59b..e4d7337ef72 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -4,6 +4,7 @@
))]
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
+use common_enums::EntityType;
use common_utils::{errors::CustomResult, id_type};
use diesel_models::enums::IntentStatus;
use error_stack::ResultExt;
@@ -663,11 +664,17 @@ pub async fn list_countries_currencies_for_connector_payment_method(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 95b65e5be57..f249285c554 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -6,6 +6,7 @@ pub mod helpers;
use actix_web::{web, Responder};
use api_models::payments::HeaderPayload;
+use common_enums::EntityType;
use error_stack::report;
use masking::PeekInterface;
use router_env::{env, instrument, logger, tracing, types, Flow};
@@ -149,7 +150,10 @@ pub async fn payments_create(
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth {
+ permission: Permission::PaymentWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
},
@@ -309,7 +313,10 @@ pub async fn payments_retrieve(
},
auth::auth_type(
&*auth_type,
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
locking_action,
@@ -1016,7 +1023,10 @@ pub async fn payments_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -1073,7 +1083,10 @@ pub async fn profile_payments_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -1103,7 +1116,10 @@ pub async fn payments_list_by_filter(
req,
)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1132,7 +1148,10 @@ pub async fn profile_payments_list_by_filter(
req,
)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1155,7 +1174,10 @@ pub async fn get_filters_for_payments(
|state, auth: auth::AuthenticationData, req, _| {
payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1176,7 +1198,10 @@ pub async fn get_payment_filters(
|state, auth: auth::AuthenticationData, _, _| {
payments::get_payment_filters(state, auth.merchant_account, None)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1201,7 +1226,10 @@ pub async fn get_payment_filters_profile(
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1224,7 +1252,10 @@ pub async fn get_payments_aggregates(
|state, auth: auth::AuthenticationData, req, _| {
payments::get_aggregates_for_payments(state, auth.merchant_account, req)
},
- &auth::JWTAuth(Permission::PaymentRead),
+ &auth::JWTAuth {
+ permission: Permission::PaymentRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -1275,7 +1306,10 @@ pub async fn payments_approve(
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth {
+ permission: Permission::PaymentWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
http_req.headers(),
),
},
@@ -1331,7 +1365,10 @@ pub async fn payments_reject(
env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth),
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth {
+ permission: Permission::PaymentWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
http_req.headers(),
),
},
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 8c45f9fdfd9..50c18d71f2a 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -2,6 +2,7 @@ use actix_web::{
body::{BoxBody, MessageBody},
web, HttpRequest, HttpResponse, Responder,
};
+use common_enums::EntityType;
use common_utils::consts;
use router_env::{instrument, tracing, Flow};
@@ -75,7 +76,10 @@ pub async fn payouts_retrieve(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -213,7 +217,10 @@ pub async fn payouts_list(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -248,7 +255,10 @@ pub async fn payouts_list_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -277,7 +287,10 @@ pub async fn payouts_list_by_filter(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -312,7 +325,10 @@ pub async fn payouts_list_by_filter_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -341,7 +357,10 @@ pub async fn payouts_list_available_filters_for_merchant(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -375,7 +394,10 @@ pub async fn payouts_list_available_filters_for_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::PayoutRead),
+ &auth::JWTAuth {
+ permission: Permission::PayoutRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index bdef96794f4..4b964dba626 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -47,7 +48,10 @@ pub async fn refunds_create(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundWrite),
+ &auth::JWTAuth {
+ permission: Permission::RefundWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -108,7 +112,10 @@ pub async fn refunds_retrieve(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -233,7 +240,10 @@ pub async fn refunds_list(
|state, auth, req, _| refund_list(state, auth.merchant_account, None, req),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -278,7 +288,10 @@ pub async fn refunds_list_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -316,7 +329,10 @@ pub async fn refunds_filter_list(
|state, auth, req, _| refund_filter_list(state, auth.merchant_account, req),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -349,7 +365,10 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
|state, auth, _, _| get_filters_for_refunds(state, auth.merchant_account, None),
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -391,7 +410,10 @@ pub async fn get_refunds_filters_profile(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RefundRead),
+ &auth::JWTAuth {
+ permission: Permission::RefundRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 09bf77c62ef..8533c9ddea9 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -5,6 +5,7 @@
use actix_web::{web, HttpRequest, Responder};
use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery};
+use common_enums::EntityType;
use router_env::{
tracing::{self, instrument},
Flow,
@@ -42,11 +43,17 @@ pub async fn routing_create_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -79,11 +86,17 @@ pub async fn routing_link_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -125,6 +138,7 @@ pub async fn routing_link_config(
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -132,6 +146,7 @@ pub async fn routing_link_config(
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -164,11 +179,17 @@ pub async fn routing_retrieve_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -200,11 +221,17 @@ pub async fn list_routing_configs(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -236,11 +263,17 @@ pub async fn list_routing_configs_for_profile(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -283,6 +316,7 @@ pub async fn routing_unlink_config(
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -316,11 +350,17 @@ pub async fn routing_unlink_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -355,11 +395,17 @@ pub async fn routing_update_default_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -389,11 +435,17 @@ pub async fn routing_update_default_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingWrite),
+ &auth::JWTAuth {
+ permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -426,6 +478,7 @@ pub async fn routing_retrieve_default_config(
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -433,6 +486,7 @@ pub async fn routing_retrieve_default_config(
&auth::JWTAuthProfileFromRoute {
profile_id: path,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -457,11 +511,17 @@ pub async fn routing_retrieve_default_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -491,11 +551,17 @@ pub async fn upsert_surcharge_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -522,11 +588,17 @@ pub async fn delete_surcharge_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -553,11 +625,17 @@ pub async fn retrieve_surcharge_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
)
.await
@@ -587,11 +665,17 @@ pub async fn upsert_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -619,11 +703,17 @@ pub async fn delete_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -647,11 +737,17 @@ pub async fn retrieve_decision_manager_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::SurchargeDecisionManagerRead),
+ &auth::JWTAuth {
+ permission: Permission::SurchargeDecisionManagerRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
)
.await
@@ -690,6 +786,7 @@ pub async fn routing_retrieve_linked_config(
&auth::JWTAuthProfileFromRoute {
profile_id,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -697,6 +794,7 @@ pub async fn routing_retrieve_linked_config(
&auth::JWTAuthProfileFromRoute {
profile_id,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -720,11 +818,17 @@ pub async fn routing_retrieve_linked_config(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
#[cfg(feature = "release")]
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -767,6 +871,7 @@ pub async fn routing_retrieve_linked_config(
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
req.headers(),
),
@@ -774,6 +879,7 @@ pub async fn routing_retrieve_linked_config(
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
required_permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Profile,
},
api_locking::LockAction::NotApplicable,
))
@@ -803,13 +909,19 @@ pub async fn routing_retrieve_default_config_for_profiles(
#[cfg(not(feature = "release"))]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
#[cfg(feature = "release")]
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::RoutingRead),
+ &auth::JWTAuth {
+ permission: Permission::RoutingRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -851,6 +963,7 @@ pub async fn routing_update_default_config_for_profile(
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -858,6 +971,7 @@ pub async fn routing_update_default_config_for_profile(
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
required_permission: Permission::RoutingWrite,
+ minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index dfc25c68945..85850c39e30 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -5,7 +5,7 @@ use api_models::{
errors::types::ApiErrorResponse,
user::{self as user_api},
};
-use common_enums::TokenPurpose;
+use common_enums::{EntityType, TokenPurpose};
use common_utils::errors::ReportSwitchExt;
use router_env::Flow;
@@ -175,7 +175,10 @@ pub async fn set_dashboard_metadata(
&req,
payload,
user_core::dashboard_metadata::set_metadata,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -257,7 +260,10 @@ pub async fn user_merchant_account_create(
|state, auth: auth::UserFromToken, json_payload, _| {
user_core::create_merchant_account(state, auth, json_payload)
},
- &auth::JWTAuth(Permission::MerchantAccountCreate),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountCreate,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -278,7 +284,10 @@ pub async fn generate_sample_data(
&http_req,
payload.into_inner(),
sample_data::generate_sample_data_for_user,
- &auth::JWTAuth(Permission::PaymentWrite),
+ &auth::JWTAuth {
+ permission: Permission::PaymentWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -298,7 +307,10 @@ pub async fn delete_sample_data(
&http_req,
payload.into_inner(),
sample_data::delete_sample_data_for_user,
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -330,7 +342,10 @@ pub async fn get_user_role_details(
&req,
payload.into_inner(),
user_core::get_user_details_in_merchant_account,
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -348,7 +363,10 @@ pub async fn list_user_roles_details(
&req,
payload.into_inner(),
user_core::list_user_roles_details,
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -365,7 +383,10 @@ pub async fn list_users_for_merchant_account(
&req,
(),
|state, user, _, _| user_core::list_users_for_merchant_account(state, user),
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -445,7 +466,10 @@ pub async fn invite_multiple_user(
|state, user, payload, req_state| {
user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -468,7 +492,10 @@ pub async fn resend_invite(
|state, user, req_payload, _| {
user_core::resend_invite(state, user, req_payload, auth_id.clone())
},
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 35c9098edd2..00b289b0b80 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,6 +1,6 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user_role::{self as user_role_api, role as role_api};
-use common_enums::TokenPurpose;
+use common_enums::{EntityType, TokenPurpose};
use router_env::Flow;
use super::AppState;
@@ -29,7 +29,10 @@ pub async fn get_authorization_info(
|state, _: (), _, _| async move {
user_role_core::get_authorization_info_with_groups(state).await
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -64,7 +67,10 @@ pub async fn create_role(
&req,
json_payload.into_inner(),
role_core::create_role,
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -80,7 +86,10 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt
|state, user, _, _| async move {
role_core::list_invitable_roles_with_groups(state, user).await
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -103,7 +112,10 @@ pub async fn get_role(
|state, user, payload, _| async move {
role_core::get_role_with_groups(state, user, payload).await
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -124,7 +136,10 @@ pub async fn update_role(
&req,
json_payload.into_inner(),
|state, user, req, _| role_core::update_role(state, user, req, &role_id),
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -143,7 +158,10 @@ pub async fn update_user_role(
&req,
payload,
user_role_core::update_user_role,
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -241,7 +259,10 @@ pub async fn delete_user_role(
&req,
payload.into_inner(),
user_role_core::delete_user_role,
- &auth::JWTAuth(Permission::UsersWrite),
+ &auth::JWTAuth {
+ permission: Permission::UsersWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -261,7 +282,9 @@ pub async fn get_role_information(
|_, _: (), _, _| async move {
user_role_core::get_authorization_info_with_group_tag().await
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth{
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant},
api_locking::LockAction::NotApplicable,
))
.await
@@ -293,7 +316,10 @@ pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest)
&req,
(),
|state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token),
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -319,7 +345,10 @@ pub async fn list_invitable_roles_at_entity_level(
role_api::RoleCheckType::Invite,
)
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
@@ -345,7 +374,10 @@ pub async fn list_updatable_roles_at_entity_level(
role_api::RoleCheckType::Update,
)
},
- &auth::JWTAuth(Permission::UsersRead),
+ &auth::JWTAuth {
+ permission: Permission::UsersRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index b818fcfc1d4..f2996009f82 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -1,5 +1,6 @@
use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -32,7 +33,10 @@ pub async fn apple_pay_merchant_registration(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ minimum_entity_level: EntityType::Profile,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
@@ -64,7 +68,10 @@ pub async fn retrieve_apple_pay_verified_domains(
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth(Permission::MerchantAccountRead),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ minimum_entity_level: EntityType::Merchant,
+ },
req.headers(),
),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs
index b510ba29637..29f8c154bc0 100644
--- a/crates/router/src/routes/verify_connector.rs
+++ b/crates/router/src/routes/verify_connector.rs
@@ -1,5 +1,6 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::verify_connector::VerifyConnectorRequest;
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::AppState;
@@ -23,7 +24,10 @@ pub async fn payment_connector_verify(
|state, auth: auth::AuthenticationData, req, _| {
verify_connector::verify_connector_credentials(state, req, auth.profile_id)
},
- &auth::JWTAuth(Permission::MerchantConnectorAccountWrite),
+ &auth::JWTAuth {
+ permission: Permission::MerchantConnectorAccountWrite,
+ minimum_entity_level: EntityType::Merchant,
+ },
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs
index d5150ad1fef..8b94fb61f56 100644
--- a/crates/router/src/routes/webhook_events.rs
+++ b/crates/router/src/routes/webhook_events.rs
@@ -1,4 +1,5 @@
use actix_web::{web, HttpRequest, Responder};
+use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use crate::{
@@ -44,6 +45,7 @@ pub async fn list_initial_webhook_delivery_attempts(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::WebhookEventRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -83,6 +85,7 @@ pub async fn list_webhook_delivery_attempts(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::WebhookEventRead,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -122,6 +125,7 @@ pub async fn retry_webhook_delivery_attempt(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::WebhookEventWrite,
+ minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 4f9a222db5e..6d100ab3576 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -10,7 +10,7 @@ use api_models::payment_methods::PaymentMethodIntentConfirm;
use api_models::payouts;
use api_models::{payment_methods::PaymentMethodListRequest, payments};
use async_trait::async_trait;
-use common_enums::TokenPurpose;
+use common_enums::{EntityType, TokenPurpose};
use common_utils::{date_time, id_type};
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
@@ -1004,12 +1004,9 @@ where
}
#[derive(Debug)]
-pub(crate) struct JWTAuth(pub Permission);
-
-#[derive(serde::Deserialize)]
-struct JwtAuthPayloadFetchUnit {
- #[serde(rename(deserialize = "exp"))]
- _exp: u64,
+pub(crate) struct JWTAuth {
+ pub permission: Permission,
+ pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1027,8 +1024,9 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.0, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
Ok((
(),
@@ -1056,8 +1054,9 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.0, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
Ok((
UserFromToken {
@@ -1091,8 +1090,10 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.0, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -1132,10 +1133,12 @@ where
pub struct JWTAuthMerchantFromRoute {
pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
+ pub minimum_entity_level: EntityType,
}
pub struct JWTAuthMerchantFromHeader {
pub required_permission: Permission,
+ pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1153,8 +1156,9 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
let merchant_id_from_header =
HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?;
@@ -1188,8 +1192,9 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
let merchant_id_from_header =
HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?;
@@ -1254,8 +1259,9 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
// Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
@@ -1290,8 +1296,10 @@ where
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -1333,6 +1341,7 @@ pub struct JWTAuthMerchantAndProfileFromRoute {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
+ pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1362,8 +1371,10 @@ where
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -1406,6 +1417,7 @@ where
pub struct JWTAuthProfileFromRoute {
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
+ pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1423,8 +1435,10 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.required_permission, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.required_permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -1517,8 +1531,10 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.0, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -1574,8 +1590,10 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- let permissions = authorization::get_permissions(state, &payload).await?;
- authorization::check_authorization(&self.0, &permissions)?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+ authorization::check_entity(self.minimum_entity_level, &role_info)?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index ea1264bde06..78af4c00884 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -1,6 +1,5 @@
use std::sync::Arc;
-use common_enums::PermissionGroup;
use common_utils::id_type;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
@@ -19,69 +18,57 @@ pub mod permission_groups;
pub mod permissions;
pub mod roles;
-pub async fn get_permissions<A>(
- state: &A,
- token: &AuthToken,
-) -> RouterResult<Vec<permissions::Permission>>
+pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
- if let Some(permissions) = get_permissions_from_predefined_roles(&token.role_id) {
- return Ok(permissions);
+ if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
+ return Ok(role_info.clone());
}
- if let Ok(permissions) = get_permissions_from_cache(state, &token.role_id)
+ if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id)
.await
.map_err(|e| logger::error!("Failed to get permissions from cache {e:?}"))
{
- return Ok(permissions);
+ return Ok(role_info.clone());
}
- let permissions =
- get_permissions_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?;
+ let role_info =
+ get_role_info_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?;
let token_expiry =
i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?;
let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp();
- set_permissions_in_cache(state, &token.role_id, &permissions, cache_ttl)
+ set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl)
.await
- .map_err(|e| logger::error!("Failed to set permissions in cache {e:?}"))
+ .map_err(|e| logger::error!("Failed to set role info in cache {e:?}"))
.ok();
- Ok(permissions)
+ Ok(role_info)
}
-async fn get_permissions_from_cache<A>(
- state: &A,
- role_id: &str,
-) -> RouterResult<Vec<permissions::Permission>>
+async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
redis_conn
- .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "Vec<Permission>")
+ .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "RoleInfo")
.await
.change_context(ApiErrorResponse::InternalServerError)
}
pub fn get_cache_key_from_role_id(role_id: &str) -> String {
- format!("{}{}", consts::ROLE_CACHE_PREFIX, role_id)
+ format!("{}{}", consts::ROLE_INFO_CACHE_PREFIX, role_id)
}
-fn get_permissions_from_predefined_roles(role_id: &str) -> Option<Vec<permissions::Permission>> {
- roles::predefined_roles::PREDEFINED_ROLES
- .get(role_id)
- .map(|role_info| get_permissions_from_groups(role_info.get_permission_groups()))
-}
-
-async fn get_permissions_from_db<A>(
+async fn get_role_info_from_db<A>(
state: &A,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
-) -> RouterResult<Vec<permissions::Permission>>
+) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
@@ -89,14 +76,14 @@ where
.store()
.find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
.await
- .map(|role| get_permissions_from_groups(&role.groups))
+ .map(roles::RoleInfo::from)
.to_not_found_response(ApiErrorResponse::InvalidJwtToken)
}
-pub async fn set_permissions_in_cache<A>(
+pub async fn set_role_info_in_cache<A>(
state: &A,
role_id: &str,
- permissions: &Vec<permissions::Permission>,
+ role_info: &roles::RoleInfo,
expiry: i64,
) -> RouterResult<()>
where
@@ -105,32 +92,17 @@ where
let redis_conn = get_redis_connection(state)?;
redis_conn
- .serialize_and_set_key_with_expiry(
- &get_cache_key_from_role_id(role_id),
- permissions,
- expiry,
- )
+ .serialize_and_set_key_with_expiry(&get_cache_key_from_role_id(role_id), role_info, expiry)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
-pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> {
- groups
- .iter()
- .flat_map(|group| {
- permission_groups::get_permissions_vec(group)
- .iter()
- .cloned()
- })
- .collect()
-}
-
-pub fn check_authorization(
+pub fn check_permission(
required_permission: &permissions::Permission,
- permissions: &[permissions::Permission],
+ role_info: &roles::RoleInfo,
) -> RouterResult<()> {
- permissions
- .contains(required_permission)
+ role_info
+ .check_permission_exists(required_permission)
.then_some(())
.ok_or(
ApiErrorResponse::AccessForbidden {
@@ -140,6 +112,18 @@ pub fn check_authorization(
)
}
+pub fn check_entity(
+ required_minimum_entity: common_enums::EntityType,
+ role_info: &roles::RoleInfo,
+) -> RouterResult<()> {
+ if required_minimum_entity > role_info.get_entity_type() {
+ Err(ApiErrorResponse::AccessForbidden {
+ resource: required_minimum_entity.to_string(),
+ })?;
+ }
+ Ok(())
+}
+
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 9b506cc5ef7..c498a33614e 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -8,7 +8,7 @@ use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
-#[derive(Clone)]
+#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct RoleInfo {
role_id: String,
role_name: String,
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index f5320c41335..9d55c5b2d16 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -215,5 +215,24 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
is_internal: false,
},
);
+ roles.insert(
+ consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT,
+ RoleInfo {
+ groups: vec![
+ PermissionGroup::OperationsView,
+ PermissionGroup::OperationsManage,
+ PermissionGroup::ConnectorsView,
+ PermissionGroup::WorkflowsView,
+ ],
+ role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(),
+ role_name: "profile_support".to_string(),
+ scope: RoleScope::Organization,
+ entity_type: EntityType::Profile,
+ is_invitable: true,
+ is_deletable: true,
+ is_updatable: true,
+ is_internal: false,
+ },
+ );
roles
});
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index ecf12742e32..cf02d7766b5 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -156,10 +156,10 @@ pub async fn set_role_permissions_in_cache_if_required(
.change_context(UserErrors::InternalServerError)
.attach_printable("Error getting role_info from role_id")?;
- authz::set_permissions_in_cache(
+ authz::set_role_info_in_cache(
state,
role_id,
- &role_info.get_permissions_set().into_iter().collect(),
+ &role_info,
i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS)
.change_context(UserErrors::InternalServerError)?,
)
| 2024-09-05T13:54:50Z |
## Description
- Created a profile level user.
- Added entity level authorization in routes.
<!-- Describe your changes in detail -->
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Dashboards users to be restricted at profile level.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
Dashboard UI.
1. Login to dashboard.
2. Invite a user at profile level.
3. Login using profile level user.
4. Check if APIs are working.
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
--> | 4d499038c03986a6f3ecee742c5add1c55789b01 | Dashboard UI.
1. Login to dashboard.
2. Invite a user at profile level.
3. Login using profile level user.
4. Check if APIs are working.
| [
"crates/router/src/analytics.rs",
"crates/router/src/consts.rs",
"crates/router/src/consts/user_role.rs",
"crates/router/src/routes/admin.rs",
"crates/router/src/routes/api_keys.rs",
"crates/router/src/routes/blocklist.rs",
"crates/router/src/routes/connector_onboarding.rs",
"crates/router/src/routes/... | |
juspay/hyperswitch | juspay__hyperswitch-5816 | Bug: feat(users): Add profile id in JWT and user_info
Currently tokens doesn't have profile id. Backend should start sending it or else dashboard will not work at profile level. | diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 4674abf3976..7bb8409993d 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_enums::{PermissionGroup, RoleScope, TokenPurpose};
+use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
@@ -158,6 +158,8 @@ pub struct GetUserDetailsResponse {
pub org_id: id_type::OrganizationId,
pub is_two_factor_auth_setup: bool,
pub recovery_codes_left: Option<usize>,
+ pub profile_id: id_type::ProfileId,
+ pub entity_type: EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -185,7 +187,7 @@ pub struct GetUserRoleDetailsResponseV2 {
pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>,
pub profile: Option<NameIdUnit<String, id_type::ProfileId>>,
pub status: UserStatus,
- pub entity_type: common_enums::EntityType,
+ pub entity_type: EntityType,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 828dfeb20f8..22aa80a459a 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -63,5 +63,5 @@ pub enum RoleCheckType {
#[derive(Debug, serde::Serialize, Clone)]
pub struct MinimalRoleInfo {
pub role_id: String,
- pub role_name: String,
+ pub role_name: Option<String>,
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 1d235dceaea..dac6027aa19 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -100,6 +100,14 @@ pub async fn get_user_details(
) -> UserResponse<user_api::GetUserDetailsResponse> {
let user = user_from_token.get_user_from_db(&state).await?;
let verification_days_left = utils::user::get_verification_days_left(&state, &user)?;
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(
user_api::GetUserDetailsResponse {
@@ -112,6 +120,10 @@ pub async fn get_user_details(
org_id: user_from_token.org_id,
is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set,
recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()),
+ profile_id: user_from_token
+ .profile_id
+ .ok_or(UserErrors::JwtProfileIdMissing)?,
+ entity_type: role_info.get_entity_type(),
},
))
}
@@ -1185,13 +1197,12 @@ pub async fn switch_merchant_id(
})?
.organization_id;
- let token = utils::user::generate_jwt_auth_token_with_attributes(
+ let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile(
&state,
user_from_token.user_id,
request.merchant_id.clone(),
org_id.clone(),
user_from_token.role_id.clone(),
- None,
)
.await?;
@@ -2792,7 +2803,6 @@ pub async fn switch_org_for_user(
.into());
}
- let key_manager_state = &(&state).into();
let role_info = roles::RoleInfo::from_role_id(
&state,
&user_from_token.role_id,
@@ -2830,38 +2840,8 @@ pub async fn switch_org_for_user(
"No user role found for the requested org_id".to_string(),
))?;
- let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?;
-
- let profile_id = if let Some(profile_id) = &user_role.profile_id {
- profile_id.clone()
- } else {
- let merchant_key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
-
- state
- .store
- .list_business_profile_by_merchant_id(
- key_manager_state,
- &merchant_key_store,
- &merchant_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list business profiles by merchant_id")?
- .pop()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No business profile found for the merchant_id")?
- .get_id()
- .to_owned()
- };
+ let (merchant_id, profile_id) =
+ utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?;
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
@@ -2869,7 +2849,7 @@ pub async fn switch_org_for_user(
merchant_id.clone(),
request.org_id.clone(),
user_role.role_id.clone(),
- Some(profile_id.clone()),
+ profile_id.clone(),
)
.await?;
@@ -3078,7 +3058,7 @@ pub async fn switch_merchant_for_user_in_org(
merchant_id.clone(),
org_id.clone(),
role_id.clone(),
- Some(profile_id),
+ profile_id,
)
.await?;
@@ -3183,7 +3163,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
user_from_token.merchant_id.clone(),
user_from_token.org_id.clone(),
role_id.clone(),
- Some(profile_id),
+ profile_id,
)
.await?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 8c955a09517..369ee97a02a 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -744,30 +744,6 @@ pub async fn list_users_in_lineage(
.map(|user| (user.user_id.clone(), user.email))
.collect::<HashMap<_, _>>();
- let role_info_map =
- futures::future::try_join_all(user_roles_set.iter().map(|user_role| async {
- roles::RoleInfo::from_role_id(
- &state,
- &user_role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .map(|role_info| {
- (
- user_role.role_id.clone(),
- user_role_api::role::MinimalRoleInfo {
- role_id: user_role.role_id.clone(),
- role_name: role_info.get_role_name().to_string(),
- },
- )
- })
- }))
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect::<HashMap<_, _>>();
-
let user_role_map = user_roles_set
.into_iter()
.fold(HashMap::new(), |mut map, user_role| {
@@ -787,13 +763,11 @@ pub async fn list_users_in_lineage(
.ok_or(UserErrors::InternalServerError)?,
roles: role_id_vec
.into_iter()
- .map(|role_id| {
- role_info_map
- .get(&role_id)
- .cloned()
- .ok_or(UserErrors::InternalServerError)
+ .map(|role_id| user_role_api::role::MinimalRoleInfo {
+ role_id,
+ role_name: None,
})
- .collect::<Result<Vec<_>, _>>()?,
+ .collect(),
})
})
.collect::<Result<Vec<_>, _>>()?,
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 1a81c49d5a9..8c9cd1da0ab 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level(
if check_type && role_info.get_entity_type() == req.entity_type {
Some(role_api::MinimalRoleInfo {
role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
+ role_name: Some(role_info.get_role_name().to_string()),
})
} else {
None
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 36af30cd9fa..2a8e3563fb6 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -5,7 +5,7 @@ use api_models::{
};
use common_enums::EntityType;
use common_utils::{
- crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
+ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
};
use diesel_models::{
@@ -28,7 +28,7 @@ use crate::{
consts,
core::{
admin,
- errors::{self, UserErrors, UserResult},
+ errors::{UserErrors, UserResult},
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
@@ -867,22 +867,6 @@ impl UserFromStorage {
self.0.email.clone()
}
- pub async fn get_role_from_db(&self, state: SessionState) -> UserResult<UserRole> {
- state
- .store
- .find_user_role_by_user_id(&self.0.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- }
-
- pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> {
- state
- .store
- .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- }
-
#[cfg(feature = "email")]
pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> {
if self.0.is_verified {
@@ -930,21 +914,6 @@ impl UserFromStorage {
Ok(days_left_for_password_rotate.whole_days() < 0)
}
- pub async fn get_role_from_db_by_merchant_id(
- &self,
- state: &SessionState,
- merchant_id: &id_type::MerchantId,
- ) -> CustomResult<UserRole, errors::StorageError> {
- state
- .store
- .find_user_role_by_user_id_merchant_id(
- self.get_user_id(),
- merchant_id,
- UserRoleVersion::V1,
- )
- .await
- }
-
pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> {
let master_key = state.store.get_master_key();
let key_manager_state = &state.into();
@@ -1253,7 +1222,7 @@ where
}
}
- async fn insert_v1_and_v2_in_db_and_get_v1(
+ async fn insert_v1_and_v2_in_db_and_get_v2(
state: &SessionState,
v1_role: UserRoleNew,
v2_role: UserRoleNew,
@@ -1264,10 +1233,9 @@ where
.await
.change_context(UserErrors::InternalServerError)?;
- // Returning v1 role so other code which was not migrated doesn't break
inserted_roles
.into_iter()
- .find(|role| role.version == UserRoleVersion::V1)
+ .find(|role| role.version == UserRoleVersion::V2)
.ok_or(report!(UserErrors::InternalServerError))
}
}
@@ -1323,7 +1291,7 @@ impl NewUserRole<OrganizationLevel> {
entity_type: EntityType::Organization,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
@@ -1343,7 +1311,7 @@ impl NewUserRole<MerchantLevel> {
entity_type: EntityType::Merchant,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
@@ -1366,7 +1334,7 @@ impl NewUserRole<InternalLevel> {
entity_type: EntityType::Internal,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index af9918af673..3fc05285ea8 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -1,8 +1,5 @@
use common_enums::TokenPurpose;
-use diesel_models::{
- enums::{UserRoleVersion, UserStatus},
- user_role::UserRole,
-};
+use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::{report, ResultExt};
use masking::Secret;
@@ -67,10 +64,21 @@ impl SPTFlow {
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
- Self::MerchantSelect => user
- .get_roles_from_db(state)
+ Self::MerchantSelect => Ok(state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user.get_user_id(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
.await
- .map(|roles| !roles.iter().any(|role| role.status == UserStatus::Active)),
+ .change_context(UserErrors::InternalServerError)?
+ .is_empty()),
}
}
@@ -105,15 +113,17 @@ impl JWTFlow {
Ok(true)
}
- pub async fn generate_jwt_without_profile(
+ pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
+ let (merchant_id, profile_id) =
+ utils::user_role::get_single_merchant_id_and_profile_id(state, user_role).await?;
auth::AuthToken::new_token(
next_flow.user.get_user_id().to_string(),
- utils::user_role::get_single_merchant_id(state, user_role).await?,
+ merchant_id,
user_role.role_id.clone(),
&state.conf,
user_role
@@ -121,7 +131,7 @@ impl JWTFlow {
.clone()
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found")?,
- None,
+ Some(profile_id),
)
.await
.map(|token| token.into())
@@ -296,7 +306,7 @@ impl NextFlow {
merchant_id: None,
profile_id: None,
entity_id: None,
- version: Some(UserRoleVersion::V1),
+ version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
@@ -307,9 +317,7 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
.await;
- jwt_flow
- .generate_jwt_without_profile(state, self, &user_role)
- .await
+ jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
@@ -329,9 +337,7 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role)
.await;
- jwt_flow
- .generate_jwt_without_profile(state, self, user_role)
- .await
+ jwt_flow.generate_jwt(state, self, user_role).await
}
}
}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index a1bd6972dab..3da24f2be7d 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -108,13 +108,25 @@ pub async fn generate_jwt_auth_token_without_profile(
Ok(Secret::new(token))
}
+pub async fn generate_jwt_auth_token_with_attributes_without_profile(
+ state: &SessionState,
+ user_id: String,
+ merchant_id: id_type::MerchantId,
+ org_id: id_type::OrganizationId,
+ role_id: String,
+) -> UserResult<Secret<String>> {
+ let token =
+ AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?;
+ Ok(Secret::new(token))
+}
+
pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
- profile_id: Option<id_type::ProfileId>,
+ profile_id: id_type::ProfileId,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user_id,
@@ -122,7 +134,7 @@ pub async fn generate_jwt_auth_token_with_attributes(
role_id,
&state.conf,
org_id,
- profile_id,
+ Some(profile_id),
)
.await?;
Ok(Secret::new(token))
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index aeb866d8d03..ecf12742e32 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -358,3 +358,42 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
}
}
}
+
+pub async fn get_single_merchant_id_and_profile_id(
+ state: &SessionState,
+ user_role: &UserRole,
+) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> {
+ let merchant_id = get_single_merchant_id(state, user_role).await?;
+ let (_, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)?;
+ let profile_id = match entity_type {
+ EntityType::Organization | EntityType::Merchant | EntityType::Internal => {
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ &state.into(),
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ state
+ .store
+ .list_business_profile_by_merchant_id(&state.into(), &key_store, &merchant_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(UserErrors::InternalServerError)?
+ .get_id()
+ .to_owned()
+ }
+ EntityType::Profile => user_role
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ };
+
+ Ok((merchant_id, profile_id))
+}
| 2024-09-05T11:52:56Z |
## Description
<!-- Describe your changes in detail -->
1. This PR changes list users in lineage API so that it don't do any db call to get the role info which leads us to send null in role name in the response.
2. This PR will add profile_id in JWT and user info API.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
3. `crates/router/src/configs`
4. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #5816.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "name"
}
'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "totp"
}
```
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: ••••••'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "user_info"
}
```
The user info token should have profile_id.
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer JWT with profile id'
```
```
{
"merchant_id": "juspay",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_hyDLeoUiRctzT45RG6vF",
"is_two_factor_auth_setup": false,
"recovery_codes_left": null,
"profile_id": "pro_chs9bTt49POqaQBeMdq4",
"entity_type": "organization"
}
``` | dfebc29c2b1398ac8934bd350eefcd4fa4f10d84 |
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "name"
}
'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "totp"
}
```
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: ••••••'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "user_info"
}
```
The user info token should have profile_id.
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer JWT with profile id'
```
```
{
"merchant_id": "juspay",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_hyDLeoUiRctzT45RG6vF",
"is_two_factor_auth_setup": false,
"recovery_codes_left": null,
"profile_id": "pro_chs9bTt49POqaQBeMdq4",
"entity_type": "organization"
}
```
| [
"crates/api_models/src/user.rs",
"crates/api_models/src/user_role/role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/types/domain/user.rs",
"crates/router/src/types/domain/user/decision_manager.rs",
"crates/... | |
juspay/hyperswitch | juspay__hyperswitch-5815 | Bug: fix(user_roles): List users in lineage API failing
List users in lineage API sends response like following:
```json
[
{
"email": "e1",
"roles": [
{
"role_id": "r1",
"role_name": "name",
}
]
}
]
```
To get the role name, this API does a db call to get the role info in the JWT merchant scope.
But if org admin is hitting this API we should also have to get the role_name from other merchant scopes which this API is not doing currently.
Temporarily fix will be don't send role name.
Permanent fix should also see in other merchant scopes. | diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 4674abf3976..7bb8409993d 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_enums::{PermissionGroup, RoleScope, TokenPurpose};
+use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
@@ -158,6 +158,8 @@ pub struct GetUserDetailsResponse {
pub org_id: id_type::OrganizationId,
pub is_two_factor_auth_setup: bool,
pub recovery_codes_left: Option<usize>,
+ pub profile_id: id_type::ProfileId,
+ pub entity_type: EntityType,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -185,7 +187,7 @@ pub struct GetUserRoleDetailsResponseV2 {
pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>,
pub profile: Option<NameIdUnit<String, id_type::ProfileId>>,
pub status: UserStatus,
- pub entity_type: common_enums::EntityType,
+ pub entity_type: EntityType,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 828dfeb20f8..22aa80a459a 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -63,5 +63,5 @@ pub enum RoleCheckType {
#[derive(Debug, serde::Serialize, Clone)]
pub struct MinimalRoleInfo {
pub role_id: String,
- pub role_name: String,
+ pub role_name: Option<String>,
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 1d235dceaea..dac6027aa19 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -100,6 +100,14 @@ pub async fn get_user_details(
) -> UserResponse<user_api::GetUserDetailsResponse> {
let user = user_from_token.get_user_from_db(&state).await?;
let verification_days_left = utils::user::get_verification_days_left(&state, &user)?;
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &user_from_token.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(
user_api::GetUserDetailsResponse {
@@ -112,6 +120,10 @@ pub async fn get_user_details(
org_id: user_from_token.org_id,
is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set,
recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()),
+ profile_id: user_from_token
+ .profile_id
+ .ok_or(UserErrors::JwtProfileIdMissing)?,
+ entity_type: role_info.get_entity_type(),
},
))
}
@@ -1185,13 +1197,12 @@ pub async fn switch_merchant_id(
})?
.organization_id;
- let token = utils::user::generate_jwt_auth_token_with_attributes(
+ let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile(
&state,
user_from_token.user_id,
request.merchant_id.clone(),
org_id.clone(),
user_from_token.role_id.clone(),
- None,
)
.await?;
@@ -2792,7 +2803,6 @@ pub async fn switch_org_for_user(
.into());
}
- let key_manager_state = &(&state).into();
let role_info = roles::RoleInfo::from_role_id(
&state,
&user_from_token.role_id,
@@ -2830,38 +2840,8 @@ pub async fn switch_org_for_user(
"No user role found for the requested org_id".to_string(),
))?;
- let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?;
-
- let profile_id = if let Some(profile_id) = &user_role.profile_id {
- profile_id.clone()
- } else {
- let merchant_key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to retrieve merchant key store by merchant_id")?;
-
- state
- .store
- .list_business_profile_by_merchant_id(
- key_manager_state,
- &merchant_key_store,
- &merchant_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to list business profiles by merchant_id")?
- .pop()
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("No business profile found for the merchant_id")?
- .get_id()
- .to_owned()
- };
+ let (merchant_id, profile_id) =
+ utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?;
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
@@ -2869,7 +2849,7 @@ pub async fn switch_org_for_user(
merchant_id.clone(),
request.org_id.clone(),
user_role.role_id.clone(),
- Some(profile_id.clone()),
+ profile_id.clone(),
)
.await?;
@@ -3078,7 +3058,7 @@ pub async fn switch_merchant_for_user_in_org(
merchant_id.clone(),
org_id.clone(),
role_id.clone(),
- Some(profile_id),
+ profile_id,
)
.await?;
@@ -3183,7 +3163,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
user_from_token.merchant_id.clone(),
user_from_token.org_id.clone(),
role_id.clone(),
- Some(profile_id),
+ profile_id,
)
.await?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 8c955a09517..369ee97a02a 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -744,30 +744,6 @@ pub async fn list_users_in_lineage(
.map(|user| (user.user_id.clone(), user.email))
.collect::<HashMap<_, _>>();
- let role_info_map =
- futures::future::try_join_all(user_roles_set.iter().map(|user_role| async {
- roles::RoleInfo::from_role_id(
- &state,
- &user_role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .map(|role_info| {
- (
- user_role.role_id.clone(),
- user_role_api::role::MinimalRoleInfo {
- role_id: user_role.role_id.clone(),
- role_name: role_info.get_role_name().to_string(),
- },
- )
- })
- }))
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect::<HashMap<_, _>>();
-
let user_role_map = user_roles_set
.into_iter()
.fold(HashMap::new(), |mut map, user_role| {
@@ -787,13 +763,11 @@ pub async fn list_users_in_lineage(
.ok_or(UserErrors::InternalServerError)?,
roles: role_id_vec
.into_iter()
- .map(|role_id| {
- role_info_map
- .get(&role_id)
- .cloned()
- .ok_or(UserErrors::InternalServerError)
+ .map(|role_id| user_role_api::role::MinimalRoleInfo {
+ role_id,
+ role_name: None,
})
- .collect::<Result<Vec<_>, _>>()?,
+ .collect(),
})
})
.collect::<Result<Vec<_>, _>>()?,
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 1a81c49d5a9..8c9cd1da0ab 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level(
if check_type && role_info.get_entity_type() == req.entity_type {
Some(role_api::MinimalRoleInfo {
role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
+ role_name: Some(role_info.get_role_name().to_string()),
})
} else {
None
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 36af30cd9fa..2a8e3563fb6 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -5,7 +5,7 @@ use api_models::{
};
use common_enums::EntityType;
use common_utils::{
- crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name,
+ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name,
types::keymanager::Identifier,
};
use diesel_models::{
@@ -28,7 +28,7 @@ use crate::{
consts,
core::{
admin,
- errors::{self, UserErrors, UserResult},
+ errors::{UserErrors, UserResult},
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
@@ -867,22 +867,6 @@ impl UserFromStorage {
self.0.email.clone()
}
- pub async fn get_role_from_db(&self, state: SessionState) -> UserResult<UserRole> {
- state
- .store
- .find_user_role_by_user_id(&self.0.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- }
-
- pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> {
- state
- .store
- .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- }
-
#[cfg(feature = "email")]
pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> {
if self.0.is_verified {
@@ -930,21 +914,6 @@ impl UserFromStorage {
Ok(days_left_for_password_rotate.whole_days() < 0)
}
- pub async fn get_role_from_db_by_merchant_id(
- &self,
- state: &SessionState,
- merchant_id: &id_type::MerchantId,
- ) -> CustomResult<UserRole, errors::StorageError> {
- state
- .store
- .find_user_role_by_user_id_merchant_id(
- self.get_user_id(),
- merchant_id,
- UserRoleVersion::V1,
- )
- .await
- }
-
pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> {
let master_key = state.store.get_master_key();
let key_manager_state = &state.into();
@@ -1253,7 +1222,7 @@ where
}
}
- async fn insert_v1_and_v2_in_db_and_get_v1(
+ async fn insert_v1_and_v2_in_db_and_get_v2(
state: &SessionState,
v1_role: UserRoleNew,
v2_role: UserRoleNew,
@@ -1264,10 +1233,9 @@ where
.await
.change_context(UserErrors::InternalServerError)?;
- // Returning v1 role so other code which was not migrated doesn't break
inserted_roles
.into_iter()
- .find(|role| role.version == UserRoleVersion::V1)
+ .find(|role| role.version == UserRoleVersion::V2)
.ok_or(report!(UserErrors::InternalServerError))
}
}
@@ -1323,7 +1291,7 @@ impl NewUserRole<OrganizationLevel> {
entity_type: EntityType::Organization,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
@@ -1343,7 +1311,7 @@ impl NewUserRole<MerchantLevel> {
entity_type: EntityType::Merchant,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
@@ -1366,7 +1334,7 @@ impl NewUserRole<InternalLevel> {
entity_type: EntityType::Internal,
});
- Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await
+ Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await
}
}
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index af9918af673..3fc05285ea8 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -1,8 +1,5 @@
use common_enums::TokenPurpose;
-use diesel_models::{
- enums::{UserRoleVersion, UserStatus},
- user_role::UserRole,
-};
+use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::{report, ResultExt};
use masking::Secret;
@@ -67,10 +64,21 @@ impl SPTFlow {
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
- Self::MerchantSelect => user
- .get_roles_from_db(state)
+ Self::MerchantSelect => Ok(state
+ .store
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user.get_user_id(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: Some(UserStatus::Active),
+ limit: Some(1),
+ })
.await
- .map(|roles| !roles.iter().any(|role| role.status == UserStatus::Active)),
+ .change_context(UserErrors::InternalServerError)?
+ .is_empty()),
}
}
@@ -105,15 +113,17 @@ impl JWTFlow {
Ok(true)
}
- pub async fn generate_jwt_without_profile(
+ pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
+ let (merchant_id, profile_id) =
+ utils::user_role::get_single_merchant_id_and_profile_id(state, user_role).await?;
auth::AuthToken::new_token(
next_flow.user.get_user_id().to_string(),
- utils::user_role::get_single_merchant_id(state, user_role).await?,
+ merchant_id,
user_role.role_id.clone(),
&state.conf,
user_role
@@ -121,7 +131,7 @@ impl JWTFlow {
.clone()
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found")?,
- None,
+ Some(profile_id),
)
.await
.map(|token| token.into())
@@ -296,7 +306,7 @@ impl NextFlow {
merchant_id: None,
profile_id: None,
entity_id: None,
- version: Some(UserRoleVersion::V1),
+ version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
@@ -307,9 +317,7 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role)
.await;
- jwt_flow
- .generate_jwt_without_profile(state, self, &user_role)
- .await
+ jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
@@ -329,9 +337,7 @@ impl NextFlow {
utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role)
.await;
- jwt_flow
- .generate_jwt_without_profile(state, self, user_role)
- .await
+ jwt_flow.generate_jwt(state, self, user_role).await
}
}
}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index a1bd6972dab..3da24f2be7d 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -108,13 +108,25 @@ pub async fn generate_jwt_auth_token_without_profile(
Ok(Secret::new(token))
}
+pub async fn generate_jwt_auth_token_with_attributes_without_profile(
+ state: &SessionState,
+ user_id: String,
+ merchant_id: id_type::MerchantId,
+ org_id: id_type::OrganizationId,
+ role_id: String,
+) -> UserResult<Secret<String>> {
+ let token =
+ AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?;
+ Ok(Secret::new(token))
+}
+
pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
- profile_id: Option<id_type::ProfileId>,
+ profile_id: id_type::ProfileId,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user_id,
@@ -122,7 +134,7 @@ pub async fn generate_jwt_auth_token_with_attributes(
role_id,
&state.conf,
org_id,
- profile_id,
+ Some(profile_id),
)
.await?;
Ok(Secret::new(token))
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index aeb866d8d03..ecf12742e32 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -358,3 +358,42 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
}
}
}
+
+pub async fn get_single_merchant_id_and_profile_id(
+ state: &SessionState,
+ user_role: &UserRole,
+) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> {
+ let merchant_id = get_single_merchant_id(state, user_role).await?;
+ let (_, entity_type) = user_role
+ .get_entity_id_and_type()
+ .ok_or(UserErrors::InternalServerError)?;
+ let profile_id = match entity_type {
+ EntityType::Organization | EntityType::Merchant | EntityType::Internal => {
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ &state.into(),
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ state
+ .store
+ .list_business_profile_by_merchant_id(&state.into(), &key_store, &merchant_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .pop()
+ .ok_or(UserErrors::InternalServerError)?
+ .get_id()
+ .to_owned()
+ }
+ EntityType::Profile => user_role
+ .profile_id
+ .clone()
+ .ok_or(UserErrors::InternalServerError)?,
+ };
+
+ Ok((merchant_id, profile_id))
+}
| 2024-09-05T11:52:56Z |
## Description
<!-- Describe your changes in detail -->
1. This PR changes list users in lineage API so that it don't do any db call to get the role info which leads us to send null in role name in the response.
2. This PR will add profile_id in JWT and user info API.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
3. `crates/router/src/configs`
4. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #5816.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "name"
}
'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "totp"
}
```
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: ••••••'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "user_info"
}
```
The user info token should have profile_id.
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer JWT with profile id'
```
```
{
"merchant_id": "juspay",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_hyDLeoUiRctzT45RG6vF",
"is_two_factor_auth_setup": false,
"recovery_codes_left": null,
"profile_id": "pro_chs9bTt49POqaQBeMdq4",
"entity_type": "organization"
}
``` | dfebc29c2b1398ac8934bd350eefcd4fa4f10d84 |
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "name"
}
'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "totp"
}
```
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: ••••••'
```
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y",
"token_type": "user_info"
}
```
The user info token should have profile_id.
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer JWT with profile id'
```
```
{
"merchant_id": "juspay",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_hyDLeoUiRctzT45RG6vF",
"is_two_factor_auth_setup": false,
"recovery_codes_left": null,
"profile_id": "pro_chs9bTt49POqaQBeMdq4",
"entity_type": "organization"
}
```
| [
"crates/api_models/src/user.rs",
"crates/api_models/src/user_role/role.rs",
"crates/router/src/core/user.rs",
"crates/router/src/core/user_role.rs",
"crates/router/src/core/user_role/role.rs",
"crates/router/src/types/domain/user.rs",
"crates/router/src/types/domain/user/decision_manager.rs",
"crates/... | |
juspay/hyperswitch | juspay__hyperswitch-4933 | Bug: Refactor `/payment_methods` to support a unified interface for vaulting use-cases
### Feature Description
We want a unified interface to `/payment_methods` create APIs for vaulting a payment method. Request/Response types and their behavior should be same across the vaulting APIs.
Involved APIs would be PM create and PM save.
### Possible Implementation
Can involve -
- refactoring of Req/Res (and other relevant types) for vaulting APIs
- refactoring of core logic for vaulting APIs | diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 00c12b9255b..c16b1d9a418 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -20,7 +20,7 @@ v1 = ["common_utils/v1"]
v2 = ["common_utils/v2", "customer_v2"]
customer_v2 = ["common_utils/customer_v2"]
payment_v2 = []
-payment_methods_v2 = []
+payment_methods_v2 = ["common_utils/payment_methods_v2"]
[dependencies]
actix-web = { version = "4.5.1", optional = true }
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 58727a46cf3..13966c464d5 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -152,3 +152,21 @@ impl<T> ApiEventMetric for MetricsResponse<T> {
Some(ApiEventsType::Miscellaneous)
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl ApiEventMetric for PaymentMethodIntentConfirmInternal {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.id.clone(),
+ payment_method: Some(self.payment_method),
+ payment_method_type: Some(self.payment_method_type),
+ })
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl ApiEventMetric for PaymentMethodIntentCreate {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethodCreate)
+ }
+}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index c6cf6380150..6c93b0bb5bd 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -160,8 +160,68 @@ pub struct PaymentMethodIntentConfirm {
/// Payment method data to be passed
pub payment_method_data: PaymentMethodCreateData,
+
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = PaymentMethodType,example = "credit")]
+ pub payment_method_type: api_enums::PaymentMethodType,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodIntentConfirm {
+ pub fn validate_payment_method_data_against_payment_method(
+ payment_method: api_enums::PaymentMethod,
+ payment_method_data: PaymentMethodCreateData,
+ ) -> bool {
+ match payment_method {
+ api_enums::PaymentMethod::Card => {
+ matches!(payment_method_data, PaymentMethodCreateData::Card(_))
+ }
+ _ => false,
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodIntentConfirmInternal {
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub id: String,
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = PaymentMethodType,example = "credit")]
+ pub payment_method_type: api_enums::PaymentMethodType,
+
+ /// For SDK based calls, client_secret would be required
+ pub client_secret: String,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: Option<id_type::CustomerId>,
+
+ /// Payment method data to be passed
+ pub payment_method_data: PaymentMethodCreateData,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm {
+ fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
+ Self {
+ client_secret: item.client_secret,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ customer_id: item.customer_id,
+ payment_method_data: item.payment_method_data.clone(),
+ }
+ }
+}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
/// This struct is only used by and internal api to migrate payment method
pub struct PaymentMethodMigrate {
@@ -276,11 +336,16 @@ impl PaymentMethodCreate {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethodCreate {
- pub fn get_payment_method_create_from_payment_method_migrate(
- _card_number: CardNumber,
- _payment_method_migrate: &PaymentMethodMigrate,
- ) -> Self {
- todo!()
+ pub fn validate_payment_method_data_against_payment_method(
+ payment_method: api_enums::PaymentMethod,
+ payment_method_data: PaymentMethodCreateData,
+ ) -> bool {
+ match payment_method {
+ api_enums::PaymentMethod::Card => {
+ matches!(payment_method_data, PaymentMethodCreateData::Card(_))
+ }
+ _ => false,
+ }
}
}
@@ -332,12 +397,6 @@ pub enum PaymentMethodUpdateData {
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Bank)]
- BankTransfer(payouts::Bank),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Wallet)]
- Wallet(payouts::Wallet),
}
#[cfg(all(
@@ -577,9 +636,6 @@ impl CardDetailUpdate {
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodResponseData {
Card(CardDetailFromLocker),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Bank)]
- Bank(payouts::Bank),
}
#[cfg(all(
@@ -934,6 +990,25 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetail> for CardDetailsPaymentMethod {
+ fn from(item: CardDetail) -> Self {
+ Self {
+ issuer_country: item.card_issuing_country.map(|c| c.to_string()),
+ last4_digits: Some(item.card_number.get_last4()),
+ expiry_month: Some(item.card_exp_month),
+ expiry_year: Some(item.card_exp_year),
+ card_holder_name: item.card_holder_name,
+ nick_name: item.nick_name,
+ card_isin: None,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type.map(|card| card.to_string()),
+ saved_to_locker: true,
+ }
+ }
+}
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index c6e29801b2f..fdc9670045e 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -21,6 +21,7 @@ payouts = ["common_enums/payouts"]
v1 = []
v2 = []
customer_v2 = []
+payment_methods_v2 = []
[dependencies]
async-trait = { version = "0.1.79", optional = true }
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 1e752a0f9b9..16d0fd9b30a 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -27,6 +27,8 @@ pub enum ApiEventsType {
payment_method: Option<PaymentMethod>,
payment_method_type: Option<PaymentMethodType>,
},
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ PaymentMethodCreate,
#[cfg(all(feature = "v2", feature = "customer_v2"))]
Customer {
id: String,
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 14738811835..20dc423310a 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -12,6 +12,8 @@ mod profile;
mod routing;
mod global_id;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+mod payment_methods;
pub use customer::CustomerId;
use diesel::{
@@ -25,6 +27,8 @@ pub use merchant::MerchantId;
pub use merchant_connector_account::MerchantConnectorAccountId;
pub use organization::OrganizationId;
pub use payment::PaymentId;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub use payment_methods::GlobalPaymentMethodId;
pub use profile::ProfileId;
pub use routing::RoutingId;
use serde::{Deserialize, Serialize};
diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs
index f04bfc3f92b..8efbc3636f9 100644
--- a/crates/common_utils/src/id_type/global_id.rs
+++ b/crates/common_utils/src/id_type/global_id.rs
@@ -21,6 +21,7 @@ pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>)
pub(crate) enum GlobalEntity {
Customer,
Payment,
+ PaymentMethod,
}
impl GlobalEntity {
@@ -28,6 +29,7 @@ impl GlobalEntity {
match self {
Self::Customer => "cus",
Self::Payment => "pay",
+ Self::PaymentMethod => "pm",
}
}
}
diff --git a/crates/common_utils/src/id_type/payment_methods.rs b/crates/common_utils/src/id_type/payment_methods.rs
new file mode 100644
index 00000000000..f5cc2150913
--- /dev/null
+++ b/crates/common_utils/src/id_type/payment_methods.rs
@@ -0,0 +1,85 @@
+use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types};
+use error_stack::ResultExt;
+
+use crate::{
+ errors,
+ errors::CustomResult,
+ id_type::global_id::{CellId, GlobalEntity, GlobalId, GlobalIdError},
+};
+
+#[derive(
+ Debug,
+ Clone,
+ Hash,
+ PartialEq,
+ Eq,
+ serde::Serialize,
+ serde::Deserialize,
+ diesel::expression::AsExpression,
+)]
+#[diesel(sql_type = diesel::sql_types::Text)]
+pub struct GlobalPaymentMethodId(GlobalId);
+
+#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
+pub enum GlobalPaymentMethodIdError {
+ #[error("Failed to construct GlobalPaymentMethodId")]
+ ConstructionError,
+}
+
+impl GlobalPaymentMethodId {
+ fn get_global_id(&self) -> &GlobalId {
+ &self.0
+ }
+ /// Create a new GlobalPaymentMethodId from celll id information
+ pub fn generate(cell_id: &str) -> error_stack::Result<Self, errors::ValidationError> {
+ let cell_id = CellId::from_string(cell_id.to_string())?;
+ let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
+ Ok(Self(global_id))
+ }
+
+ pub fn get_string_repr(&self) -> String {
+ todo!()
+ }
+
+ pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
+ let id = GlobalId::from_string(value)
+ .change_context(GlobalPaymentMethodIdError::ConstructionError)?;
+ Ok(Self(id))
+ }
+}
+
+impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: diesel::backend::Backend,
+ Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
+{
+ type Row = Self;
+ fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
+ Ok(row)
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: Backend,
+ GlobalId: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(
+ &'b self,
+ out: &mut diesel::serialize::Output<'b, '_, DB>,
+ ) -> diesel::serialize::Result {
+ let id = self.get_global_id();
+ id.to_sql(out)
+ }
+}
+
+impl<DB> FromSql<sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: Backend,
+ GlobalId: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ let global_id = GlobalId::from_sql(value)?;
+ Ok(Self(global_id))
+ }
+}
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ca919eb15da..3ad58e62dcf 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -88,7 +88,7 @@ pub struct PaymentMethod {
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -105,7 +105,7 @@ impl PaymentMethod {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
@@ -179,7 +179,7 @@ pub struct PaymentMethodNew {
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -200,7 +200,7 @@ impl PaymentMethodNew {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 37c41c19dd9..321c7a6829c 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -211,7 +211,10 @@ impl PaymentMethod {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethod {
- pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {
+ pub async fn find_by_id(
+ conn: &PgPooledConn,
+ id: &common_utils::id_type::GlobalPaymentMethodId,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
.await
}
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index e7cbae9e88c..af3c657c34a 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -77,7 +77,7 @@ pub struct PaymentMethod {
pub payment_method_billing_address: OptionalEncryptableValue,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -94,7 +94,7 @@ impl PaymentMethod {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 0c6e06cc42d..bae6243d2e6 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -37,7 +37,7 @@ v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"]
-payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2"]
+payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 3d4a29e0f30..1f4fd00bbc5 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -135,3 +135,15 @@ pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong";
// Recon's feature tag
pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT";
+
+/// Vault Add request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const ADD_VAULT_REQUEST_URL: &str = "/vault/add";
+
+/// Vault Get Fingerprint request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint";
+
+/// Vault Header content type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d8a28ebdf2e..c56bfaca913 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -148,6 +148,12 @@ pub enum VaultError {
SavePaymentMethodFailed,
#[error("Failed to generate fingerprint")]
GenerateFingerprintFailed,
+ #[error("Failed to encrypt vault request")]
+ RequestEncryptionFailed,
+ #[error("Failed to decrypt vault response")]
+ ResponseDecryptionFailed,
+ #[error("Failed to call vault")]
+ VaultAPIError,
#[error("Failed while calling locker API")]
ApiError,
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 72fbc3d3d4e..fa7ddfce997 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -21,9 +21,16 @@ use api_models::payment_methods;
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::ext_traits::Encode;
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-use common_utils::ext_traits::OptionExt;
use common_utils::{consts::DEFAULT_LOCALE, id_type::CustomerId};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::{
+ crypto::{self, Encryptable},
+ ext_traits::{AsyncExt, Encode, ValueExt},
+ fp_utils::when,
+ generate_id, id_type,
+ request::RequestContent,
+ types as util_types,
+};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
@@ -31,7 +38,11 @@ use error_stack::{report, ResultExt};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use masking::ExposeInterface;
use masking::PeekInterface;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use masking::Secret;
use router_env::{instrument, tracing};
use time::Duration;
@@ -39,11 +50,25 @@ use super::{
errors::{RouterResponse, StorageErrorExt},
pm_auth,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ configs::settings,
+ core::{payment_methods::transformers as pm_transforms, utils as core_utils},
+ headers, logger,
+ routes::payment_methods as pm_routes,
+ services::encryption,
+ types::{
+ api::{self, payment_methods::PaymentMethodCreateExt},
+ payment_methods as pm_types,
+ storage::PaymentMethodListContext,
+ },
+ utils::ext_traits::OptionExt,
+};
use crate::{
consts,
core::{
errors::{self, RouterResult},
- payments::helpers,
+ payments::helpers as payment_helpers,
},
routes::{app::StorageInterface, SessionState},
services,
@@ -67,7 +92,7 @@ pub async fn retrieve_payment_method(
) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> {
match pm_data {
pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -81,7 +106,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -104,7 +129,7 @@ pub async fn retrieve_payment_method(
pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -118,7 +143,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -132,7 +157,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -414,6 +439,10 @@ fn generate_task_id_for_payment_method_status_update_workflow(
format!("{runner}_{task}_{key_id}")
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
@@ -483,7 +512,10 @@ pub async fn retrieve_payment_method_with_token(
todo!()
}
-#[cfg(feature = "v1")]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_with_token(
@@ -500,7 +532,7 @@ pub async fn retrieve_payment_method_with_token(
) -> RouterResult<storage::PaymentMethodDataWithId> {
let token = match token_data {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
+ payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
@@ -519,7 +551,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::Temporary(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
+ payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
@@ -538,7 +570,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::Permanent(card_token) => {
- helpers::retrieve_card_with_permanent_token(
+ payment_helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
@@ -572,7 +604,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::PermanentCard(card_token) => {
- helpers::retrieve_card_with_permanent_token(
+ payment_helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
@@ -793,3 +825,950 @@ pub(crate) async fn get_payment_method_create_request(
.attach_printable("PaymentMethodData required Or Card is already saved")),
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn create_payment_method(
+ state: &SessionState,
+ req: api::PaymentMethodCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ req.validate()?;
+
+ let db = &*state.store;
+ let merchant_id = merchant_account.get_id();
+ let customer_id = req.customer_id.to_owned();
+
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
+ .billing
+ .clone()
+ .async_map(|billing| cards::create_encrypted_data(state, key_store, billing))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method billing address")?;
+
+ // create pm
+ let payment_method_id =
+ common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = create_payment_method_for_intent(
+ state,
+ req.metadata.clone(),
+ &customer_id,
+ payment_method_id,
+ merchant_id,
+ key_store,
+ merchant_account.storage_scheme,
+ payment_method_billing_address.map(Into::into),
+ )
+ .await
+ .attach_printable("Failed to add Payment method to DB")?;
+
+ let vaulting_result =
+ vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+
+ let response = match vaulting_result {
+ Ok(resp) => {
+ let pm_update = create_pm_additional_data_update(
+ &req.payment_method_data,
+ state,
+ key_store,
+ Some(resp.vault_id),
+ Some(req.payment_method),
+ Some(req.payment_method_type),
+ )
+ .await
+ .attach_printable("Unable to create Payment method data")?;
+
+ let payment_method = db
+ .update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ let resp = pm_transforms::generate_payment_method_response(&payment_method)?;
+
+ Ok(resp)
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ Err(e)
+ }
+ }?;
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn payment_method_intent_create(
+ state: &SessionState,
+ req: api::PaymentMethodIntentCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+ let merchant_id = merchant_account.get_id();
+ let customer_id = req.customer_id.to_owned();
+
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
+ .billing
+ .clone()
+ .async_map(|billing| cards::create_encrypted_data(state, key_store, billing))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method billing address")?;
+
+ // create pm entry
+
+ let payment_method_id =
+ common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = create_payment_method_for_intent(
+ state,
+ req.metadata.clone(),
+ &customer_id,
+ payment_method_id,
+ merchant_id,
+ key_store,
+ merchant_account.storage_scheme,
+ payment_method_billing_address.map(Into::into),
+ )
+ .await
+ .attach_printable("Failed to add Payment method to DB")?;
+
+ let resp = pm_transforms::generate_payment_method_response(&payment_method)?;
+
+ Ok(services::ApplicationResponse::Json(resp))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn payment_method_intent_confirm(
+ state: &SessionState,
+ req: api::PaymentMethodIntentConfirm,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ pm_id: String,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ req.validate()?;
+
+ let db = &*state.store;
+ let client_secret = req.client_secret.clone();
+ let pm_id = common_utils::id_type::GlobalPaymentMethodId::generate_from_string(pm_id)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = db
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Unable to find payment method")?;
+
+ when(
+ cards::authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?,
+ || Err(errors::ApiErrorResponse::ClientSecretExpired),
+ )?;
+
+ when(
+ payment_method.status != enums::PaymentMethodStatus::AwaitingData,
+ || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid pm_id provided: This Payment method cannot be confirmed"
+ .to_string(),
+ })
+ },
+ )?;
+
+ let customer_id = payment_method.customer_id.to_owned();
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let vaulting_result =
+ vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+
+ let response = match vaulting_result {
+ Ok(resp) => {
+ let pm_update = create_pm_additional_data_update(
+ &req.payment_method_data,
+ state,
+ key_store,
+ Some(resp.vault_id),
+ Some(req.payment_method),
+ Some(req.payment_method_type),
+ )
+ .await
+ .attach_printable("Unable to create Payment method data")?;
+
+ let payment_method = db
+ .update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ let resp = pm_transforms::generate_payment_method_response(&payment_method)?;
+
+ Ok(resp)
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ Err(e)
+ }
+ }?;
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn create_payment_method_in_db(
+ state: &SessionState,
+ req: &api::PaymentMethodCreate,
+ customer_id: &id_type::CustomerId,
+ payment_method_id: id_type::GlobalPaymentMethodId,
+ locker_id: Option<String>,
+ merchant_id: &id_type::MerchantId,
+ pm_metadata: Option<common_utils::pii::SecretSerdeValue>,
+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
+ payment_method_data: crypto::OptionalEncryptableValue,
+ key_store: &domain::MerchantKeyStore,
+ connector_mandate_details: Option<common_utils::pii::SecretSerdeValue>,
+ status: Option<enums::PaymentMethodStatus>,
+ network_transaction_id: Option<String>,
+ storage_scheme: enums::MerchantStorageScheme,
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
+ card_scheme: Option<String>,
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id);
+ let current_time = common_utils::date_time::now();
+
+ let response = db
+ .insert_payment_method(
+ &state.into(),
+ key_store,
+ domain::PaymentMethod {
+ customer_id: customer_id.to_owned(),
+ merchant_id: merchant_id.to_owned(),
+ id: payment_method_id,
+ locker_id,
+ payment_method: Some(req.payment_method),
+ payment_method_type: Some(req.payment_method_type),
+ metadata: pm_metadata,
+ payment_method_data,
+ connector_mandate_details,
+ customer_acceptance,
+ client_secret: Some(client_secret),
+ status: status.unwrap_or(enums::PaymentMethodStatus::Active),
+ network_transaction_id: network_transaction_id.to_owned(),
+ created_at: current_time,
+ last_modified: current_time,
+ last_used_at: current_time,
+ payment_method_billing_address,
+ updated_by: None,
+ version: domain::consts::API_VERSION,
+ locker_fingerprint_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ network_token_requestor_reference_id: None,
+ },
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ Ok(response)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn create_payment_method_for_intent(
+ state: &SessionState,
+ metadata: Option<common_utils::pii::SecretSerdeValue>,
+ customer_id: &id_type::CustomerId,
+ payment_method_id: id_type::GlobalPaymentMethodId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id);
+ let current_time = common_utils::date_time::now();
+
+ let response = db
+ .insert_payment_method(
+ &state.into(),
+ key_store,
+ domain::PaymentMethod {
+ customer_id: customer_id.to_owned(),
+ merchant_id: merchant_id.to_owned(),
+ id: payment_method_id,
+ locker_id: None,
+ payment_method: None,
+ payment_method_type: None,
+ metadata,
+ payment_method_data: None,
+ connector_mandate_details: None,
+ customer_acceptance: None,
+ client_secret: Some(client_secret),
+ status: enums::PaymentMethodStatus::AwaitingData,
+ network_transaction_id: None,
+ created_at: current_time,
+ last_modified: current_time,
+ last_used_at: current_time,
+ payment_method_billing_address,
+ updated_by: None,
+ version: domain::consts::API_VERSION,
+ locker_fingerprint_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ network_token_requestor_reference_id: None,
+ },
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ Ok(response)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn create_pm_additional_data_update(
+ pmd: &api::PaymentMethodCreateData,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ vault_id: Option<String>,
+ payment_method: Option<api_enums::PaymentMethod>,
+ payment_method_type: Option<api_enums::PaymentMethodType>,
+) -> errors::RouterResult<storage::PaymentMethodUpdate> {
+ let card = match pmd.clone() {
+ api::PaymentMethodCreateData::Card(card) => api::PaymentMethodsData::Card(card.into()),
+ };
+
+ let pmd: Encryptable<Secret<serde_json::Value>> =
+ cards::create_encrypted_data(state, key_store, card)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method data")?;
+
+ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
+ status: Some(enums::PaymentMethodStatus::Active),
+ locker_id: vault_id,
+ payment_method,
+ payment_method_type,
+ payment_method_data: Some(pmd).map(Into::into),
+ network_token_requestor_reference_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ };
+
+ Ok(pm_update)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn vault_payment_method(
+ state: &SessionState,
+ pmd: &api::PaymentMethodCreateData,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<pm_types::AddVaultResponse> {
+ let db = &*state.store;
+
+ // get fingerprint_id from locker
+ let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd)
+ .await
+ .attach_printable("Failed to get fingerprint_id from vault")?;
+
+ // throw back error if payment method is duplicated
+ when(
+ Some(
+ db.find_payment_method_by_fingerprint_id(
+ &(state.into()),
+ key_store,
+ &fingerprint_id_from_locker,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to find payment method by fingerprint_id")?,
+ )
+ .is_some(),
+ || {
+ Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod)
+ .attach_printable("Cannot vault duplicate payment method"))
+ },
+ )?;
+
+ let resp_from_locker =
+ cards::vault_payment_method_in_locker(state, merchant_account, pmd).await?;
+
+ Ok(resp_from_locker)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+async fn get_pm_list_context(
+ state: &SessionState,
+ payment_method: &enums::PaymentMethod,
+ _key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
+ _parent_payment_method_token: Option<String>,
+ is_payment_associated: bool,
+) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
+ let payment_method_retrieval_context = match payment_method {
+ enums::PaymentMethod::Card => {
+ let card_details = cards::get_card_details_with_locker_fallback(pm, state).await?;
+
+ card_details.as_ref().map(|card| PaymentMethodListContext {
+ card_details: Some(card.clone()),
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ storage::PaymentTokenData::permanent_card(
+ Some(pm.get_id().clone()),
+ pm.locker_id.clone().or(Some(pm.get_id().get_string_repr())),
+ pm.locker_id
+ .clone()
+ .unwrap_or(pm.get_id().get_string_repr()),
+ ),
+ ),
+ })
+ }
+
+ enums::PaymentMethod::BankDebit => {
+ // Retrieve the pm_auth connector details so that it can be tokenized
+ let bank_account_token_data = cards::get_bank_account_connector_details(pm)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ });
+
+ bank_account_token_data.map(|data| {
+ let token_data = storage::PaymentTokenData::AuthBankDebit(data);
+
+ PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(token_data),
+ }
+ })
+ }
+
+ _ => Some(PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ storage::PaymentTokenData::temporary_generic(generate_id(
+ consts::ID_LENGTH,
+ "token",
+ )),
+ ),
+ }),
+ };
+
+ Ok(payment_method_retrieval_context)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+pub async fn list_customer_payment_method_util(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ req: Option<api::PaymentMethodListRequest>,
+ customer_id: Option<id_type::CustomerId>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let limit = req.as_ref().and_then(|pml_req| pml_req.limit);
+
+ let (customer_id, payment_intent) = if is_payment_associated {
+ let cloned_secret = req.and_then(|r| r.client_secret.clone());
+ let payment_intent = payment_helpers::verify_payment_intent_time_and_client_secret(
+ &state,
+ &merchant_account,
+ &key_store,
+ cloned_secret,
+ )
+ .await?;
+
+ (
+ payment_intent
+ .as_ref()
+ .and_then(|pi| pi.customer_id.clone()),
+ payment_intent,
+ )
+ } else {
+ (customer_id, None)
+ };
+
+ let resp = if let Some(cust) = customer_id {
+ Box::pin(list_customer_payment_method(
+ &state,
+ merchant_account,
+ key_store,
+ payment_intent,
+ &cust,
+ limit,
+ is_payment_associated,
+ ))
+ .await?
+ } else {
+ let response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: Vec::new(),
+ is_guest_customer: Some(true),
+ };
+ services::ApplicationResponse::Json(response)
+ };
+
+ Ok(resp)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+pub async fn list_customer_payment_method(
+ state: &SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ payment_intent: Option<storage::PaymentIntent>,
+ customer_id: &id_type::CustomerId,
+ limit: Option<i64>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(state).into();
+ // let key = key_store.key.get_inner().peek();
+
+ let customer = db
+ .find_customer_by_merchant_reference_id_merchant_id(
+ key_manager_state,
+ customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payments_info = payment_intent
+ .async_map(|pi| {
+ pm_types::SavedPMLPaymentsInfo::form_payments_info(
+ pi,
+ &merchant_account,
+ db,
+ key_manager_state,
+ &key_store,
+ )
+ })
+ .await
+ .transpose()?;
+
+ let saved_payment_methods = db
+ .find_payment_method_by_customer_id_merchant_id_status(
+ key_manager_state,
+ &key_store,
+ customer_id,
+ merchant_account.get_id(),
+ common_enums::PaymentMethodStatus::Active,
+ limit,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let mut filtered_saved_payment_methods_ctx = Vec::new();
+ for pm in saved_payment_methods.into_iter() {
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+ let parent_payment_method_token =
+ is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
+
+ let pm_list_context = get_pm_list_context(
+ state,
+ &payment_method,
+ &key_store,
+ &pm,
+ parent_payment_method_token.clone(),
+ is_payment_associated,
+ )
+ .await?;
+
+ if let Some(ctx) = pm_list_context {
+ filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm));
+ }
+ }
+
+ let pm_list_futures = filtered_saved_payment_methods_ctx
+ .into_iter()
+ .map(|ctx| {
+ generate_saved_pm_response(
+ state,
+ &key_store,
+ &merchant_account,
+ ctx,
+ &customer,
+ payments_info.as_ref(),
+ )
+ })
+ .collect::<Vec<_>>();
+
+ let final_result = futures::future::join_all(pm_list_futures).await;
+
+ let mut customer_pms = Vec::new();
+ for result in final_result.into_iter() {
+ let pma = result.attach_printable("saved pm list failed")?;
+ customer_pms.push(pma);
+ }
+
+ let mut response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: customer_pms,
+ is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent
+ };
+
+ if is_payment_associated {
+ Box::pin(cards::perform_surcharge_ops(
+ payments_info.as_ref().map(|pi| pi.payment_intent.clone()),
+ state,
+ merchant_account,
+ key_store,
+ payments_info.and_then(|pi| pi.business_profile),
+ &mut response,
+ ))
+ .await?;
+ }
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn generate_saved_pm_response(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ merchant_account: &domain::MerchantAccount,
+ pm_list_context: (
+ PaymentMethodListContext,
+ Option<String>,
+ domain::PaymentMethod,
+ ),
+ customer: &domain::Customer,
+ payment_info: Option<&pm_types::SavedPMLPaymentsInfo>,
+) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> {
+ let (pm_list_context, parent_payment_method_token, pm) = pm_list_context;
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+
+ let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
+ cards::get_masked_bank_details(&pm)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
+ } else {
+ None
+ };
+
+ let payment_method_billing = pm
+ .payment_method_billing_address
+ .clone()
+ .map(|decrypted_data| decrypted_data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse payment method billing address details")?;
+
+ let connector_mandate_details = pm
+ .connector_mandate_details
+ .clone()
+ .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+
+ let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) =
+ payment_info
+ .map(|pi| {
+ (
+ pi.is_connector_agnostic_mit_enabled,
+ pi.requires_cvv,
+ pi.off_session_payment_flag,
+ pi.business_profile
+ .as_ref()
+ .map(|profile| profile.get_id().to_owned()),
+ )
+ })
+ .unwrap_or((false, false, false, Default::default()));
+
+ let mca_enabled = cards::get_mca_status(
+ state,
+ key_store,
+ profile_id,
+ merchant_account.get_id(),
+ is_connector_agnostic_mit_enabled,
+ connector_mandate_details,
+ pm.network_transaction_id.as_ref(),
+ )
+ .await?;
+
+ let requires_cvv = if is_connector_agnostic_mit_enabled {
+ requires_cvv
+ && !(off_session_payment_flag
+ && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some()))
+ } else {
+ requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
+ };
+
+ let pmd = if let Some(card) = pm_list_context.card_details.as_ref() {
+ Some(api::PaymentMethodListData::Card(card.clone()))
+ } else if cfg!(feature = "payouts") {
+ pm_list_context
+ .bank_transfer_details
+ .clone()
+ .map(api::PaymentMethodListData::Bank)
+ } else {
+ None
+ };
+
+ let pma = api::CustomerPaymentMethod {
+ payment_token: parent_payment_method_token.clone(),
+ payment_method_id: pm.get_id().get_string_repr(),
+ customer_id: pm.customer_id.to_owned(),
+ payment_method,
+ payment_method_type: pm.payment_method_type,
+ payment_method_data: pmd,
+ metadata: pm.metadata.clone(),
+ recurring_enabled: mca_enabled,
+ created: Some(pm.created_at),
+ bank: bank_details,
+ surcharge_details: None,
+ requires_cvv: requires_cvv
+ && !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
+ last_used_at: Some(pm.last_used_at),
+ is_default: customer.default_payment_method_id.is_some()
+ && customer.default_payment_method_id.as_ref() == Some(&pm.get_id().get_string_repr()),
+ billing: payment_method_billing,
+ };
+
+ payment_info
+ .async_map(|pi| {
+ pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context)
+ })
+ .await
+ .transpose()?;
+
+ Ok(pma)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl pm_types::SavedPMLPaymentsInfo {
+ pub async fn form_payments_info(
+ payment_intent: storage::PaymentIntent,
+ merchant_account: &domain::MerchantAccount,
+ db: &dyn StorageInterface,
+ key_manager_state: &util_types::keymanager::KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ ) -> errors::RouterResult<Self> {
+ let requires_cvv = db
+ .find_config_by_key_unwrap_or(
+ format!(
+ "{}_requires_cvv",
+ merchant_account.get_id().get_string_repr()
+ )
+ .as_str(),
+ Some("true".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch requires_cvv config")?
+ .config
+ != "false";
+
+ let off_session_payment_flag = matches!(
+ payment_intent.setup_future_usage,
+ Some(common_enums::FutureUsage::OffSession)
+ );
+
+ let profile_id = payment_intent
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("profile_id is not set in payment_intent")?
+ .clone();
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(profile_id).as_ref(),
+ merchant_account.get_id(),
+ )
+ .await?;
+
+ let is_connector_agnostic_mit_enabled = business_profile
+ .as_ref()
+ .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
+ .unwrap_or(false);
+
+ Ok(Self {
+ payment_intent,
+ business_profile,
+ requires_cvv,
+ off_session_payment_flag,
+ is_connector_agnostic_mit_enabled,
+ })
+ }
+
+ pub async fn perform_payment_ops(
+ &self,
+ state: &SessionState,
+ parent_payment_method_token: Option<String>,
+ pma: &api::CustomerPaymentMethod,
+ pm_list_context: PaymentMethodListContext,
+ ) -> errors::RouterResult<()> {
+ let token = parent_payment_method_token
+ .as_ref()
+ .get_required_value("parent_payment_method_token")?;
+ let hyperswitch_token_data = pm_list_context
+ .hyperswitch_token_data
+ .get_required_value("PaymentTokenData")?;
+
+ let intent_fulfillment_time = self
+ .business_profile
+ .as_ref()
+ .and_then(|b_profile| b_profile.get_order_fulfillment_time())
+ .unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME);
+
+ pm_routes::ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method))
+ .insert(intent_fulfillment_time, hyperswitch_token_data, state)
+ .await?;
+
+ if let Some(metadata) = pma.metadata.clone() {
+ let pm_metadata_vec: pm_transforms::PaymentMethodMetadata = metadata
+ .parse_value("PaymentMethodMetadata")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to deserialize metadata to PaymentmethodMetadata struct",
+ )?;
+
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ for pm_metadata in pm_metadata_vec.payment_method_tokenization {
+ let key = format!(
+ "pm_token_{}_{}_{}",
+ token, pma.payment_method, pm_metadata.0
+ );
+
+ redis_conn
+ .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add data in redis")?;
+ }
+ }
+
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 22350f77e69..79d1226f13a 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -69,8 +69,6 @@ use super::surcharge_decision_configs::{
use crate::routes::app::SessionStateInfo;
#[cfg(feature = "payouts")]
use crate::types::domain::types::AsyncLift;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use crate::utils::{self};
use crate::{
configs::{
defaults::{get_billing_required_fields, get_shipping_required_fields},
@@ -95,8 +93,14 @@ use crate::{
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::ForeignTryFrom,
},
+ utils,
utils::OptionExt,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ consts as router_consts, core::payment_methods as pm_core, headers,
+ types::payment_methods as pm_types, utils::ConnectorResponseExt,
+};
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -217,32 +221,35 @@ pub async fn create_payment_method(
Ok(response)
}
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-#[instrument(skip_all)]
-#[allow(clippy::too_many_arguments)]
-pub async fn create_payment_method(
- _state: &routes::SessionState,
- _req: &api::PaymentMethodCreate,
- _customer_id: &id_type::CustomerId,
- _payment_method_id: &str,
- _locker_id: Option<String>,
- _merchant_id: &id_type::MerchantId,
- _pm_metadata: Option<serde_json::Value>,
- _customer_acceptance: Option<serde_json::Value>,
- _payment_method_data: Option<Encryption>,
- _key_store: &domain::MerchantKeyStore,
- _connector_mandate_details: Option<serde_json::Value>,
- _status: Option<enums::PaymentMethodStatus>,
- _network_transaction_id: Option<String>,
- _storage_scheme: MerchantStorageScheme,
- _payment_method_billing_address: Option<Encryption>,
- _card_scheme: Option<String>,
-) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
- todo!()
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn create_vault_request<R: pm_types::VaultingInterface>(
+ jwekey: &settings::Jwekey,
+ locker: &settings::Locker,
+ payload: Vec<u8>,
+) -> errors::CustomResult<services::Request, errors::VaultError> {
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
+
+ let jws = services::encryption::jws_sign_payload(
+ &payload,
+ &locker.locker_signing_key_id,
+ private_key,
+ )
+ .await
+ .change_context(errors::VaultError::RequestEncryptionFailed)?;
+
+ let jwe_payload = payment_methods::create_jwe_body_for_vault(jwekey, &jws).await?;
+
+ let mut url = locker.host.to_owned();
+ url.push_str(R::get_vaulting_request_url());
+ let mut request = services::Request::new(services::Method::Post, &url);
+ request.add_header(
+ headers::CONTENT_TYPE,
+ router_consts::VAULT_HEADER_CONTENT_TYPE.into(),
+ );
+ request.set_body(common_utils::request::RequestContent::Json(Box::new(
+ jwe_payload,
+ )));
+ Ok(request)
}
#[cfg(all(
@@ -911,17 +918,6 @@ pub async fn get_client_secret_or_add_payment_method(
}
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn get_client_secret_or_add_payment_method(
- _state: &routes::SessionState,
- _req: api::PaymentMethodCreate,
- _merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
-}
-
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
@@ -1417,13 +1413,64 @@ pub async fn add_payment_method(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
-pub async fn add_payment_method(
- _state: &routes::SessionState,
- _req: api::PaymentMethodCreate,
- _merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
+pub async fn get_fingerprint_id_from_locker<
+ D: pm_types::VaultingDataInterface + serde::Serialize,
+>(
+ state: &routes::SessionState,
+ data: &D,
+) -> errors::RouterResult<String> {
+ let key = data.get_vaulting_data_key();
+ let data = serde_json::to_value(data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode Vaulting data to value")?
+ .to_string();
+
+ let payload = pm_types::VaultFingerprintRequest { key, data }
+ .encode_to_vec()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode VaultFingerprintRequest")?;
+
+ let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get response from locker")?;
+
+ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
+ .parse_struct("VaultFingerprintResp")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse data into VaultFingerprintResp")?;
+
+ Ok(fingerprint_resp.fingerprint_id)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn vault_payment_method_in_locker(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ pmd: &api::PaymentMethodCreateData,
+) -> errors::RouterResult<pm_types::AddVaultResponse> {
+ let payload = pm_types::AddVaultRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id: uuid::Uuid::now_v7().to_string(),
+ data: pmd.clone(),
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode AddVaultRequest")?;
+
+ let resp = call_to_vault::<pm_types::AddVault>(state, payload)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get response from locker")?;
+
+ let stored_pm_resp: pm_types::AddVaultResponse = resp
+ .parse_struct("AddVaultResponse")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse data into AddVaultResponse")?;
+
+ Ok(stored_pm_resp)
}
#[cfg(all(
@@ -1506,40 +1553,7 @@ pub async fn insert_payment_method(
storage_scheme: MerchantStorageScheme,
payment_method_billing_address: Option<Encryption>,
) -> errors::RouterResult<domain::PaymentMethod> {
- let pm_card_details = match &resp.payment_method_data {
- Some(api::PaymentMethodResponseData::Card(card_data)) => Some(PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card_data.clone()),
- )),
- _ => None,
- };
-
- let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details
- .clone()
- .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card))
- .await
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt payment method data")?;
-
- create_payment_method(
- state,
- req,
- customer_id,
- &resp.payment_method_id,
- locker_id,
- merchant_id,
- pm_metadata,
- customer_acceptance,
- pm_data_encrypted.map(Into::into),
- key_store,
- connector_mandate_details,
- None,
- network_transaction_id,
- storage_scheme,
- payment_method_billing_address,
- None,
- )
- .await
+ todo!()
}
#[cfg(all(
@@ -2225,6 +2239,37 @@ pub async fn add_card_to_hs_locker(
Ok(stored_card)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn call_to_vault<V: pm_types::VaultingInterface>(
+ state: &routes::SessionState,
+ payload: Vec<u8>,
+) -> errors::CustomResult<String, errors::VaultError> {
+ let locker = &state.conf.locker;
+ let jwekey = state.conf.jwekey.get_inner();
+
+ let request = create_vault_request::<V>(jwekey, locker, payload).await?;
+ let response = services::call_connector_api(state, request, "vault_in_locker")
+ .await
+ .change_context(errors::VaultError::VaultAPIError);
+
+ let jwe_body: services::JweBody = response
+ .get_response_inner("JweBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to get JweBody from vault response")?;
+
+ let decrypted_payload = payment_methods::get_decrypted_vault_response_payload(
+ jwekey,
+ jwe_body,
+ locker.decryption_scheme.clone(),
+ )
+ .await
+ .change_context(errors::VaultError::ResponseDecryptionFailed)
+ .attach_printable("Error getting decrypted vault response payload")?;
+
+ Ok(decrypted_payload)
+}
+
#[instrument(skip_all)]
pub async fn call_locker_api<T>(
state: &routes::SessionState,
@@ -3819,6 +3864,10 @@ fn should_collect_shipping_or_billing_details_from_wallet_connector(
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+))]
async fn validate_payment_method_and_client_secret(
state: &routes::SessionState,
cs: &String,
@@ -4235,63 +4284,6 @@ fn filter_recurring_based(
recurring_enabled.map_or(true, |enabled| payment_method.recurring_enabled == enabled)
}
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-pub async fn list_customer_payment_method_util(
- state: routes::SessionState,
- merchant_account: domain::MerchantAccount,
- key_store: domain::MerchantKeyStore,
- req: Option<api::PaymentMethodListRequest>,
- customer_id: Option<id_type::CustomerId>,
- is_payment_associated: bool,
-) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
- let limit = req.as_ref().and_then(|pml_req| pml_req.limit);
-
- let (customer_id, payment_intent) = if is_payment_associated {
- let cloned_secret = req.and_then(|r| r.client_secret.clone());
- let payment_intent = helpers::verify_payment_intent_time_and_client_secret(
- &state,
- &merchant_account,
- &key_store,
- cloned_secret,
- )
- .await?;
-
- (
- payment_intent
- .as_ref()
- .and_then(|pi| pi.customer_id.clone()),
- payment_intent,
- )
- } else {
- (customer_id, None)
- };
-
- let resp = if let Some(cust) = customer_id {
- Box::pin(list_customer_payment_method(
- &state,
- merchant_account,
- key_store,
- payment_intent,
- &cust,
- limit,
- is_payment_associated,
- ))
- .await?
- } else {
- let response = api::CustomerPaymentMethodsListResponse {
- customer_payment_methods: Vec::new(),
- is_guest_customer: Some(true),
- };
- services::ApplicationResponse::Json(response)
- };
-
- Ok(resp)
-}
-
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2"),
@@ -4615,6 +4607,11 @@ pub async fn list_customer_payment_method(
Ok(services::ApplicationResponse::Json(response))
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
@@ -4706,7 +4703,11 @@ async fn get_pm_list_context(
Ok(payment_method_retrieval_context)
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_v2"),
+ not(feature = "payment_methods_v2")
+))]
async fn perform_surcharge_ops(
payment_intent: Option<storage::PaymentIntent>,
state: &routes::SessionState,
@@ -4751,8 +4752,8 @@ async fn perform_surcharge_ops(
Ok(())
}
-#[cfg(all(feature = "v2", feature = "payment_v2"))]
-async fn perform_surcharge_ops(
+#[cfg(all(feature = "v2", feature = "payment_v2", feature = "payment_methods_v2"))]
+pub async fn perform_surcharge_ops(
_payment_intent: Option<storage::PaymentIntent>,
_state: &routes::SessionState,
_merchant_account: domain::MerchantAccount,
@@ -4763,370 +4764,6 @@ async fn perform_surcharge_ops(
todo!()
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-struct SavedPMLPaymentsInfo {
- pub payment_intent: storage::PaymentIntent,
- pub business_profile: Option<BusinessProfile>,
- pub requires_cvv: bool,
- pub off_session_payment_flag: bool,
- pub is_connector_agnostic_mit_enabled: bool,
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-impl SavedPMLPaymentsInfo {
- pub async fn form_payments_info(
- payment_intent: storage::PaymentIntent,
- merchant_account: &domain::MerchantAccount,
- db: &dyn db::StorageInterface,
- key_manager_state: &KeyManagerState,
- key_store: &domain::MerchantKeyStore,
- ) -> errors::RouterResult<Self> {
- let requires_cvv = db
- .find_config_by_key_unwrap_or(
- format!(
- "{}_requires_cvv",
- merchant_account.get_id().get_string_repr()
- )
- .as_str(),
- Some("true".to_string()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch requires_cvv config")?
- .config
- != "false";
-
- let off_session_payment_flag = matches!(
- payment_intent.setup_future_usage,
- Some(common_enums::FutureUsage::OffSession)
- );
-
- let profile_id = payment_intent
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("profile_id is not set in payment_intent")?
- .clone();
-
- let business_profile = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(profile_id).as_ref(),
- merchant_account.get_id(),
- )
- .await?;
-
- let is_connector_agnostic_mit_enabled = business_profile
- .as_ref()
- .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
- .unwrap_or(false);
-
- Ok(Self {
- payment_intent,
- business_profile,
- requires_cvv,
- off_session_payment_flag,
- is_connector_agnostic_mit_enabled,
- })
- }
-
- pub async fn perform_payment_ops(
- &self,
- state: &routes::SessionState,
- parent_payment_method_token: Option<String>,
- pma: &api::CustomerPaymentMethod,
- pm_list_context: PaymentMethodListContext,
- ) -> errors::RouterResult<()> {
- let token = parent_payment_method_token
- .as_ref()
- .get_required_value("parent_payment_method_token")?;
- let hyperswitch_token_data = pm_list_context
- .hyperswitch_token_data
- .get_required_value("PaymentTokenData")?;
-
- let intent_fulfillment_time = self
- .business_profile
- .as_ref()
- .and_then(|b_profile| b_profile.get_order_fulfillment_time())
- .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
-
- ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method))
- .insert(intent_fulfillment_time, hyperswitch_token_data, state)
- .await?;
-
- if let Some(metadata) = pma.metadata.clone() {
- let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata
- .parse_value("PaymentMethodMetadata")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to deserialize metadata to PaymentmethodMetadata struct",
- )?;
-
- let redis_conn = state
- .store
- .get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get redis connection")?;
-
- for pm_metadata in pm_metadata_vec.payment_method_tokenization {
- let key = format!(
- "pm_token_{}_{}_{}",
- token, pma.payment_method, pm_metadata.0
- );
-
- redis_conn
- .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)
- .await
- .change_context(errors::StorageError::KVError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add data in redis")?;
- }
- }
-
- Ok(())
- }
-}
-
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-pub async fn list_customer_payment_method(
- state: &routes::SessionState,
- merchant_account: domain::MerchantAccount,
- key_store: domain::MerchantKeyStore,
- payment_intent: Option<storage::PaymentIntent>,
- customer_id: &id_type::CustomerId,
- limit: Option<i64>,
- is_payment_associated: bool,
-) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
- let db = &*state.store;
- let key_manager_state = &(state).into();
- // let key = key_store.key.get_inner().peek();
-
- let customer = db
- .find_customer_by_merchant_reference_id_merchant_id(
- key_manager_state,
- customer_id,
- merchant_account.get_id(),
- &key_store,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
-
- let payments_info = payment_intent
- .async_map(|pi| {
- SavedPMLPaymentsInfo::form_payments_info(
- pi,
- &merchant_account,
- db,
- key_manager_state,
- &key_store,
- )
- })
- .await
- .transpose()?;
-
- let saved_payment_methods = db
- .find_payment_method_by_customer_id_merchant_id_status(
- key_manager_state,
- &key_store,
- customer_id,
- merchant_account.get_id(),
- common_enums::PaymentMethodStatus::Active,
- limit,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let mut filtered_saved_payment_methods_ctx = Vec::new();
- for pm in saved_payment_methods.into_iter() {
- logger::debug!(
- "Fetching payment method from locker for payment_method_id: {}",
- pm.id
- );
- let payment_method = pm.payment_method.get_required_value("payment_method")?;
- let parent_payment_method_token =
- is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
-
- let pm_list_context = get_pm_list_context(
- state,
- &payment_method,
- &key_store,
- &pm,
- parent_payment_method_token.clone(),
- is_payment_associated,
- )
- .await?;
-
- if let Some(ctx) = pm_list_context {
- filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm));
- }
- }
-
- let pm_list_futures = filtered_saved_payment_methods_ctx
- .into_iter()
- .map(|ctx| {
- generate_saved_pm_response(
- state,
- &key_store,
- &merchant_account,
- ctx,
- &customer,
- payments_info.as_ref(),
- )
- })
- .collect::<Vec<_>>();
-
- let final_result = futures::future::join_all(pm_list_futures).await;
-
- let mut customer_pms = Vec::new();
- for result in final_result.into_iter() {
- let pma = result.attach_printable("saved pm list failed")?;
- customer_pms.push(pma);
- }
-
- let mut response = api::CustomerPaymentMethodsListResponse {
- customer_payment_methods: customer_pms,
- is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent
- };
-
- if is_payment_associated {
- Box::pin(perform_surcharge_ops(
- payments_info.as_ref().map(|pi| pi.payment_intent.clone()),
- state,
- merchant_account,
- key_store,
- payments_info.and_then(|pi| pi.business_profile),
- &mut response,
- ))
- .await?;
- }
-
- Ok(services::ApplicationResponse::Json(response))
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-async fn generate_saved_pm_response(
- state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
- merchant_account: &domain::MerchantAccount,
- pm_list_context: (
- PaymentMethodListContext,
- Option<String>,
- domain::PaymentMethod,
- ),
- customer: &domain::Customer,
- payment_info: Option<&SavedPMLPaymentsInfo>,
-) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> {
- let (pm_list_context, parent_payment_method_token, pm) = pm_list_context;
- let payment_method = pm.payment_method.get_required_value("payment_method")?;
-
- let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
- get_masked_bank_details(&pm).await.unwrap_or_else(|err| {
- logger::error!(error=?err);
- None
- })
- } else {
- None
- };
-
- let payment_method_billing = pm
- .payment_method_billing_address
- .clone()
- .map(|decrypted_data| decrypted_data.into_inner().expose())
- .map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to parse payment method billing address details")?;
-
- let connector_mandate_details = pm
- .connector_mandate_details
- .clone()
- .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
-
- let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) =
- payment_info
- .map(|pi| {
- (
- pi.is_connector_agnostic_mit_enabled,
- pi.requires_cvv,
- pi.off_session_payment_flag,
- pi.business_profile
- .as_ref()
- .map(|profile| profile.get_id().to_owned()),
- )
- })
- .unwrap_or((false, false, false, Default::default()));
-
- let mca_enabled = get_mca_status(
- state,
- key_store,
- profile_id,
- merchant_account.get_id(),
- is_connector_agnostic_mit_enabled,
- connector_mandate_details,
- pm.network_transaction_id.as_ref(),
- )
- .await?;
-
- let requires_cvv = if is_connector_agnostic_mit_enabled {
- requires_cvv
- && !(off_session_payment_flag
- && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some()))
- } else {
- requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
- };
-
- let pmd = if let Some(card) = pm_list_context.card_details.as_ref() {
- Some(api::PaymentMethodListData::Card(card.clone()))
- } else if cfg!(feature = "payouts") {
- pm_list_context
- .bank_transfer_details
- .clone()
- .map(api::PaymentMethodListData::Bank)
- } else {
- None
- };
-
- let pma = api::CustomerPaymentMethod {
- payment_token: parent_payment_method_token.clone(),
- payment_method_id: pm.get_id().clone(),
- customer_id: pm.customer_id.to_owned(),
- payment_method,
- payment_method_type: pm.payment_method_type,
- payment_method_data: pmd,
- metadata: pm.metadata.clone(),
- recurring_enabled: mca_enabled,
- created: Some(pm.created_at),
- bank: bank_details,
- surcharge_details: None,
- requires_cvv: requires_cvv
- && !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
- last_used_at: Some(pm.last_used_at),
- is_default: customer.default_payment_method_id.is_some()
- && customer.default_payment_method_id.as_ref() == Some(pm.get_id()),
- billing: payment_method_billing,
- };
-
- payment_info
- .async_map(|pi| {
- pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context)
- })
- .await
- .transpose()?;
-
- Ok(pma)
-}
-
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
@@ -5236,24 +4873,7 @@ pub async fn get_card_details_with_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
- let card_decrypted = pm
- .payment_method_data
- .clone()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
-
- Ok(if let Some(crd) = card_decrypted {
- Some(crd)
- } else {
- logger::debug!(
- "Getting card details from locker as it is not found in payment methods table"
- );
- Some(get_card_details_from_locker(state, pm).await?)
- })
+ todo!()
}
#[cfg(all(
@@ -5290,25 +4910,13 @@ pub async fn get_card_details_without_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let card_decrypted = pm
- .payment_method_data
- .clone()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
- Ok(if let Some(crd) = card_decrypted {
- crd
- } else {
- logger::debug!(
- "Getting card details from locker as it is not found in payment methods table"
- );
- get_card_details_from_locker(state, pm).await?
- })
+ todo!()
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
@@ -5328,6 +4936,10 @@ pub async fn get_card_details_from_locker(
.attach_printable("Get Card Details Failed")
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_lookup_key_from_locker(
state: &routes::SessionState,
payment_token: &str,
@@ -5348,7 +4960,7 @@ pub async fn get_lookup_key_from_locker(
Ok(resp)
}
-async fn get_masked_bank_details(
+pub async fn get_masked_bank_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<MaskedBankDetails>> {
let payment_method_data = pm
@@ -5377,7 +4989,7 @@ async fn get_masked_bank_details(
}
}
-async fn get_bank_account_connector_details(
+pub async fn get_bank_account_connector_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let payment_method_data = pm
@@ -5604,8 +5216,16 @@ pub async fn get_bank_from_hs_locker(
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub struct TempLockerCardSupport;
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
impl TempLockerCardSupport {
#[instrument(skip_all)]
async fn create_payment_method_data_in_temp_locker(
@@ -5761,53 +5381,7 @@ pub async fn retrieve_payment_method(
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
- let db = state.store.as_ref();
- let pm = db
- .find_payment_method(
- &((&state).into()),
- &key_store,
- &pm.payment_method_id,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let card = if pm.payment_method == Some(enums::PaymentMethod::Card) {
- let card_detail = if state.conf.locker.locker_enabled {
- let card = get_card_from_locker(
- &state,
- &pm.customer_id,
- &pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(pm.get_id()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error getting card from card vault")?;
- payment_methods::get_card_detail(&pm, card)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card details from locker")?
- } else {
- get_card_details_without_locker_fallback(&pm, &state).await?
- };
- Some(card_detail)
- } else {
- None
- };
- Ok(services::ApplicationResponse::Json(
- api::PaymentMethodResponse {
- merchant_id: pm.merchant_id.to_owned(),
- customer_id: pm.customer_id.to_owned(),
- payment_method_id: pm.get_id().clone(),
- payment_method: pm.payment_method,
- payment_method_type: pm.payment_method_type,
- metadata: pm.metadata,
- created: Some(pm.created_at),
- recurring_enabled: false,
- payment_method_data: card.clone().map(api::PaymentMethodResponseData::Card),
- last_used_at: Some(pm.last_used_at),
- client_secret: pm.client_secret,
- },
- ))
+ todo!()
}
#[cfg(all(
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 17477141492..d0f63a2dc04 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -2,6 +2,8 @@
use std::str::FromStr;
use api_models::{enums as api_enums, payment_methods::Card};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::ext_traits::ValueExt;
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
@@ -249,6 +251,92 @@ pub async fn get_decrypted_response_payload(
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
+pub async fn get_decrypted_vault_response_payload(
+ jwekey: &settings::Jwekey,
+ jwe_body: encryption::JweBody,
+ decryption_scheme: settings::DecryptionScheme,
+) -> CustomResult<String, errors::VaultError> {
+ let public_key = jwekey.vault_encryption_key.peek().as_bytes();
+
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
+
+ let jwt = get_dotted_jwe(jwe_body);
+ let alg = match decryption_scheme {
+ settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
+ settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
+ };
+
+ let jwe_decrypted = encryption::decrypt_jwe(
+ &jwt,
+ encryption::KeyIdCheck::SkipKeyIdCheck,
+ private_key,
+ alg,
+ )
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jwe Decryption failed for JweBody for vault")?;
+
+ let jws = jwe_decrypted
+ .parse_struct("JwsBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)?;
+ let jws_body = get_dotted_jws(jws);
+
+ encryption::verify_sign(jws_body, public_key)
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jws Decryption failed for JwsBody for vault")
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn create_jwe_body_for_vault(
+ jwekey: &settings::Jwekey,
+ jws: &str,
+) -> CustomResult<encryption::JweBody, errors::VaultError> {
+ let jws_payload: Vec<&str> = jws.split('.').collect();
+
+ let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
+ Some(encryption::JwsBody {
+ header: payload.first()?.to_string(),
+ payload: payload.get(1)?.to_string(),
+ signature: payload.get(2)?.to_string(),
+ })
+ };
+
+ let jws_body =
+ generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
+
+ let payload = jws_body
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)?;
+
+ let public_key = jwekey.vault_encryption_key.peek().as_bytes();
+
+ let jwe_encrypted = encryption::encrypt_jwe(
+ &payload,
+ public_key,
+ encryption::EncryptionAlgorithm::A256GCM,
+ None,
+ )
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Error on jwe encrypt")?;
+ let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
+
+ let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
+ Some(encryption::JweBody {
+ header: payload.first()?.to_string(),
+ iv: payload.get(2)?.to_string(),
+ encrypted_payload: payload.get(3)?.to_string(),
+ tag: payload.get(4)?.to_string(),
+ encrypted_key: payload.get(1)?.to_string(),
+ })
+ };
+
+ let jwe_body =
+ generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
+
+ Ok(jwe_body)
+}
+
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
@@ -428,14 +516,50 @@ pub fn mk_add_card_response_hs(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub fn mk_add_card_response_hs(
- _card: api::CardDetail,
- _card_reference: String,
- _req: api::PaymentMethodCreate,
- _merchant_id: &id_type::MerchantId,
+ card: api::CardDetail,
+ card_reference: String,
+ req: api::PaymentMethodCreate,
+ merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn generate_payment_method_response(
+ pm: &domain::PaymentMethod,
+) -> errors::RouterResult<api::PaymentMethodResponse> {
+ let pmd = pm
+ .payment_method_data
+ .clone()
+ .map(|data| data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("PaymentMethodsData"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse PaymentMethodsData")?
+ .and_then(|data| match data {
+ api::PaymentMethodsData::Card(card) => {
+ Some(api::PaymentMethodResponseData::Card(card.into()))
+ }
+ _ => None,
+ });
+
+ let resp = api::PaymentMethodResponse {
+ merchant_id: pm.merchant_id.to_owned(),
+ customer_id: pm.customer_id.to_owned(),
+ payment_method_id: pm.id.get_string_repr(),
+ payment_method: pm.payment_method,
+ payment_method_type: pm.payment_method_type,
+ metadata: pm.metadata.clone(),
+ created: Some(pm.created_at),
+ recurring_enabled: false,
+ last_used_at: Some(pm.last_used_at),
+ client_secret: pm.client_secret.clone(),
+ payment_method_data: pmd,
+ };
+
+ Ok(resp)
+}
+
#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0ec14bd69ed..0af5bf6037a 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3807,6 +3807,25 @@ where
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
+ state: &SessionState,
+ payment_data: &mut D,
+ routing_data: &mut storage::RoutingData,
+ connectors: Vec<api::ConnectorData>,
+ mandate_type: Option<api::MandateTransactionType>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+) -> RouterResult<ConnectorCallType>
+where
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
@@ -3970,6 +3989,26 @@ where
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[allow(clippy::too_many_arguments)]
+pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>(
+ state: &SessionState,
+ payment_data: &mut D,
+ routing_data: &mut storage::RoutingData,
+ connectors: Vec<api::ConnectorData>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+ payment_method_info: &domain::PaymentMethod,
+) -> RouterResult<ConnectorCallType>
+where
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a1d92d8a992..ce92c1ab007 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1781,6 +1781,23 @@ pub async fn retrieve_payment_method_with_temporary_token(
})
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn retrieve_card_with_permanent_token(
+ state: &SessionState,
+ locker_id: &str,
+ _payment_method_id: &common_utils::id_type::GlobalPaymentMethodId,
+ payment_intent: &PaymentIntent,
+ card_token_data: Option<&domain::CardToken>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
+) -> RouterResult<domain::PaymentMethodData> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_card_with_permanent_token(
state: &SessionState,
@@ -1986,6 +2003,20 @@ pub async fn fetch_card_details_from_locker(
Ok(domain::PaymentMethodData::Card(api_card.into()))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn retrieve_payment_method_from_db_with_token_data(
+ state: &SessionState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ token_data: &storage::PaymentTokenData,
+ storage_scheme: storage::enums::MerchantStorageScheme,
+) -> RouterResult<Option<domain::PaymentMethod>> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
@@ -2082,6 +2113,27 @@ pub async fn retrieve_payment_token_data(
Ok(token_data)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn make_pm_data<'a, F: Clone, R, D>(
+ _operation: BoxedOperation<'a, F, R, D>,
+ _state: &'a SessionState,
+ _payment_data: &mut PaymentData<F>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _customer: &Option<domain::Customer>,
+ _storage_scheme: common_enums::enums::MerchantStorageScheme,
+ _business_profile: Option<&domain::BusinessProfile>,
+) -> RouterResult<(
+ BoxedOperation<'a, F, R, D>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+)> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn make_pm_data<'a, F: Clone, R, D>(
operation: BoxedOperation<'a, F, R, D>,
state: &'a SessionState,
@@ -5100,6 +5152,21 @@ pub fn update_additional_payment_data_with_connector_response_pm_data(
.attach_printable("Failed to encode additional pm data")
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn get_payment_method_details_from_payment_token(
+ state: &SessionState,
+ payment_attempt: &PaymentAttempt,
+ payment_intent: &PaymentIntent,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index f397ecd8a2a..a9cd1ae4d84 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -978,6 +978,35 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>> f
}
impl PaymentCreate {
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ #[allow(clippy::too_many_arguments)]
+ pub async fn make_payment_attempt(
+ payment_id: &common_utils::id_type::PaymentId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ organization_id: &common_utils::id_type::OrganizationId,
+ money: (api::Amount, enums::Currency),
+ payment_method: Option<enums::PaymentMethod>,
+ payment_method_type: Option<enums::PaymentMethodType>,
+ request: &api::PaymentsRequest,
+ browser_info: Option<serde_json::Value>,
+ state: &SessionState,
+ payment_method_billing_address_id: Option<String>,
+ payment_method_info: &Option<domain::PaymentMethod>,
+ _key_store: &domain::MerchantKeyStore,
+ profile_id: common_utils::id_type::ProfileId,
+ customer_acceptance: &Option<payments::CustomerAcceptance>,
+ ) -> RouterResult<(
+ storage::PaymentAttemptNew,
+ Option<api_models::payments::AdditionalPaymentData>,
+ )> {
+ todo!()
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index fb09b4d8b60..ae6ac330679 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -88,6 +88,26 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
Ok(payment_data)
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ business_profile: &domain::BusinessProfile,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ todo!()
+ }
+
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
@@ -1602,6 +1622,23 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn update_payment_method_status_and_ntid<F: Clone>(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ attempt_status: common_enums::AttemptStatus,
+ payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
+ storage_scheme: enums::MerchantStorageScheme,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+) -> RouterResult<()> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index d81258d6671..0760cd449fe 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -214,6 +214,28 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn get_tracker_for_sync<
+ 'a,
+ F: Send + Clone,
+ Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync,
+>(
+ _payment_id: &api::PaymentIdType,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ _state: &SessionState,
+ _request: &api::PaymentsRetrieveRequest,
+ _operation: Op,
+ _storage_scheme: enums::MerchantStorageScheme,
+) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index f948d7faaf9..2a93f8c215d 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -489,7 +489,18 @@ async fn store_bank_details_in_payment_methods(
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
let pm_id = generate_id(consts::ID_LENGTH, "pm");
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ let pm_id = common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
let now = common_utils::date_time::now();
#[cfg(all(
any(feature = "v1", feature = "v2"),
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 4dc77211857..8120ccc8089 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1821,6 +1821,10 @@ impl PaymentIntentInterface for KafkaStore {
#[async_trait::async_trait]
impl PaymentMethodInterface for KafkaStore {
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -1833,6 +1837,19 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method(state, key_store, payment_method_id, storage_scheme)
+ .await
+ }
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index cf263def41c..6e052076799 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -14,6 +14,10 @@ use crate::{
#[async_trait::async_trait]
pub trait PaymentMethodInterface {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -22,6 +26,15 @@ pub trait PaymentMethodInterface {
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+ #[cfg(all(feature = "v2", feature = "customer_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -231,7 +244,7 @@ mod storage {
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- payment_method_id: &str,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -251,7 +264,8 @@ mod storage {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("payment_method_{}", payment_method_id);
+ let lookup_id =
+ format!("payment_method_{}", payment_method_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -385,6 +399,38 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ async fn insert_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method_new = payment_method
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method_new
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
@@ -591,77 +637,18 @@ mod storage {
.await
.change_context(errors::StorageError::DecryptionError)?;
- let merchant_id = payment_method.merchant_id.clone();
- let customer_id = payment_method.customer_id.clone();
- let key = PartitionKey::MerchantIdCustomerId {
- merchant_id: &merchant_id,
- customer_id: &customer_id,
- };
- let field = format!("payment_method_id_{}", payment_method.get_id());
- let storage_scheme =
- Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
- ))
- .await;
- let pm = match storage_scheme {
- MerchantStorageScheme::PostgresOnly => {
- let conn = connection::pg_connection_write(self).await?;
- payment_method
- .update_with_id(
- &conn,
- payment_method_update.convert_to_payment_method_update(storage_scheme),
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
- MerchantStorageScheme::RedisKv => {
- let key_str = key.to_string();
-
- let p_update: PaymentMethodUpdateInternal =
- payment_method_update.convert_to_payment_method_update(storage_scheme);
- let updated_payment_method =
- p_update.clone().apply_changeset(payment_method.clone());
-
- let redis_value = serde_json::to_string(&updated_payment_method)
- .change_context(errors::StorageError::SerializationFailed)?;
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentMethodUpdate(
- kv::PaymentMethodUpdateMems {
- orig: payment_method,
- update_data: p_update,
- },
- ),
- },
- };
-
- kv_wrapper::<(), _, _>(
- self,
- KvOperation::<diesel_models::PaymentMethod>::Hset(
- (&field, redis_value),
- redis_entry,
- ),
- key,
- )
- .await
- .map_err(|err| err.to_redis_failed_response(&key_str))?
- .try_into_hset()
- .change_context(errors::StorageError::KVError)?;
-
- Ok(updated_payment_method)
- }
- }?;
-
- pm.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method
+ .update_with_id(&conn, payment_method_update.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
#[cfg(all(
@@ -927,7 +914,7 @@ mod storage {
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- payment_method_id: &str,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -1258,6 +1245,10 @@ mod storage {
#[async_trait::async_trait]
impl PaymentMethodInterface for MockDb {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -1287,6 +1278,36 @@ impl PaymentMethodInterface for MockDb {
}
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.get_id() == payment_method_id)
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2bafe504dd9..aad5acbbade 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1064,6 +1064,24 @@ impl Payouts {
}
}
+#[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2",))]
+impl PaymentMethods {
+ pub fn server(state: AppState) -> Scope {
+ let mut route = web::scope("/v2/payment_methods").app_data(web::Data::new(state));
+ route = route
+ .service(web::resource("").route(web::post().to(create_payment_method_api)))
+ .service(
+ web::resource("/create-intent")
+ .route(web::post().to(create_payment_method_intent_api)),
+ )
+ .service(
+ web::resource("/{id}/confirm-intent")
+ .route(web::post().to(confirm_payment_method_intent_api)),
+ );
+
+ route
+ }
+}
pub struct PaymentMethods;
#[cfg(all(
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index e2cb50b0aa7..725d6af81af 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -12,6 +12,11 @@ use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::core::payment_methods::{
+ create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm,
+ payment_method_intent_create,
+};
use crate::{
core::{
api_locking, errors,
@@ -35,6 +40,10 @@ use crate::{
types::api::customers::CustomerRequest,
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
@@ -63,6 +72,114 @@ pub async fn create_payment_method_api(
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn create_payment_method_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodCreate>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth, req, _| async move {
+ Box::pin(create_payment_method(
+ &state,
+ req,
+ &auth.merchant_account,
+ &auth.key_store,
+ ))
+ .await
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn create_payment_method_intent_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth, req, _| async move {
+ Box::pin(payment_method_intent_create(
+ &state,
+ req,
+ &auth.merchant_account,
+ &auth.key_store,
+ ))
+ .await
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn confirm_payment_method_intent_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodIntentConfirm>,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+ let pm_id = path.into_inner();
+ let payload = json_payload.into_inner();
+
+ let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ };
+
+ let inner_payload = payment_methods::PaymentMethodIntentConfirmInternal {
+ id: pm_id.clone(),
+ payment_method: payload.payment_method,
+ payment_method_type: payload.payment_method_type,
+ client_secret: payload.client_secret.clone(),
+ customer_id: payload.customer_id.to_owned(),
+ payment_method_data: payload.payment_method_data.clone(),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ inner_payload,
+ |state, auth, req, _| {
+ let pm_id = pm_id.clone();
+ async move {
+ Box::pin(payment_method_intent_confirm(
+ &state,
+ req.into(),
+ &auth.merchant_account,
+ &auth.key_store,
+ pm_id,
+ ))
+ .await
+ }
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
@@ -346,7 +463,7 @@ pub async fn list_customer_payment_method_for_payment(
&req,
payload,
|state, auth, req, _| {
- cards::list_customer_payment_method_util(
+ list_customer_payment_method_util(
state,
auth.merchant_account,
auth.key_store,
@@ -411,7 +528,7 @@ pub async fn list_customer_payment_method_api(
&req,
payload,
|state, auth, req, _| {
- cards::list_customer_payment_method_util(
+ list_customer_payment_method_util(
state,
auth.merchant_account,
auth.key_store,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 16a8ed1ccc4..bcc2046e24e 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -11,6 +11,7 @@ pub mod authentication;
pub mod domain;
#[cfg(feature = "frm")]
pub mod fraud_check;
+pub mod payment_methods;
pub mod pm_auth;
use masking::Secret;
pub mod storage;
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 9262877a385..b3bcfa2a887 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -125,75 +125,7 @@ impl MandateResponseExt for MandateResponse {
mandate: storage::Mandate,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<Self> {
- let db = &*state.store;
- let payment_method = db
- .find_payment_method(
- &(state.into()),
- &key_store,
- &mandate.payment_method_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let pm = payment_method
- .payment_method
- .get_required_value("payment_method")
- .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
- .attach_printable("payment_method not found")?;
-
- let card = if pm == storage_enums::PaymentMethod::Card {
- // if locker is disabled , decrypt the payment method data
- let card_details = if state.conf.locker.locker_enabled {
- let card = payment_methods::cards::get_card_from_locker(
- state,
- &payment_method.customer_id,
- &payment_method.merchant_id,
- payment_method
- .locker_id
- .as_ref()
- .unwrap_or(&payment_method.id),
- )
- .await?;
-
- payment_methods::transformers::get_card_detail(&payment_method, card)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card details")?
- } else {
- payment_methods::cards::get_card_details_without_locker_fallback(
- &payment_method,
- state,
- )
- .await?
- };
-
- Some(MandateCardDetails::from(card_details).into_inner())
- } else {
- None
- };
- let payment_method_type = payment_method
- .payment_method_type
- .map(|pmt| pmt.to_string());
- Ok(Self {
- mandate_id: mandate.mandate_id,
- customer_acceptance: Some(api::payments::CustomerAcceptance {
- acceptance_type: if mandate.customer_ip_address.is_some() {
- api::payments::AcceptanceType::Online
- } else {
- api::payments::AcceptanceType::Offline
- },
- accepted_at: mandate.customer_accepted_at,
- online: Some(api::payments::OnlineMandate {
- ip_address: mandate.customer_ip_address,
- user_agent: mandate.customer_user_agent.unwrap_or_default(),
- }),
- }),
- card,
- status: mandate.mandate_status,
- payment_method: pm.to_string(),
- payment_method_type,
- payment_method_id: mandate.payment_method_id,
- })
+ todo!()
}
}
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index f4d1492fb44..65111815b5c 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -5,8 +5,8 @@ pub use api_models::payment_methods::{
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
- PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodList,
- PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
+ PaymentMethodIntentConfirm, PaymentMethodIntentConfirmInternal, PaymentMethodIntentCreate,
+ PaymentMethodList, PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate,
PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1,
TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
@@ -32,6 +32,8 @@ use crate::core::{
errors::{self, RouterResult},
payments::helpers::validate_payment_method_type_against_payment_method,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::utils;
pub(crate) trait PaymentMethodCreateExt {
fn validate(&self) -> RouterResult<()>;
@@ -61,15 +63,63 @@ impl PaymentMethodCreateExt for PaymentMethodCreate {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
- if !validate_payment_method_type_against_payment_method(
- self.payment_method,
- self.payment_method_type,
- ) {
- return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid 'payment_method_type' provided".to_string()
- })
- .attach_printable("Invalid payment method type"));
- }
+ utils::when(
+ !validate_payment_method_type_against_payment_method(
+ self.payment_method,
+ self.payment_method_type,
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ },
+ );
+
+ utils::when(
+ !PaymentMethodCreate::validate_payment_method_data_against_payment_method(
+ self.payment_method,
+ self.payment_method_data.clone(),
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_data' provided".to_string()
+ })
+ .attach_printable("Invalid payment method data"));
+ },
+ );
+ Ok(())
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodCreateExt for PaymentMethodIntentConfirm {
+ fn validate(&self) -> RouterResult<()> {
+ utils::when(
+ !validate_payment_method_type_against_payment_method(
+ self.payment_method,
+ self.payment_method_type,
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ },
+ );
+
+ utils::when(
+ !PaymentMethodIntentConfirm::validate_payment_method_data_against_payment_method(
+ self.payment_method,
+ self.payment_method_data.clone(),
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_data' provided".to_string()
+ })
+ .attach_printable("Invalid payment method data"));
+ },
+ );
Ok(())
}
}
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
new file mode 100644
index 00000000000..933b8e73da8
--- /dev/null
+++ b/crates/router/src/types/payment_methods.rs
@@ -0,0 +1,103 @@
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::generate_id;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ consts,
+ types::{api, domain, storage},
+};
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+pub trait VaultingInterface {
+ fn get_vaulting_request_url() -> &'static str;
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+pub trait VaultingDataInterface {
+ fn get_vaulting_data_key(&self) -> String;
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultFingerprintRequest {
+ pub data: String,
+ pub key: String,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultFingerprintResponse {
+ pub fingerprint_id: String,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVaultRequest<D> {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: String,
+ pub data: D,
+ pub ttl: i64,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVaultResponse {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: String,
+ pub fingerprint_id: Option<String>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVault;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct GetVaultFingerprint;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingInterface for AddVault {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::ADD_VAULT_REQUEST_URL
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingInterface for GetVaultFingerprint {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::VAULT_FINGERPRINT_REQUEST_URL
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingDataInterface for api::PaymentMethodCreateData {
+ fn get_vaulting_data_key(&self) -> String {
+ match &self {
+ api::PaymentMethodCreateData::Card(card) => card.card_number.to_string(),
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub struct PaymentMethodClientSecret;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodClientSecret {
+ pub fn generate(payment_method_id: &common_utils::id_type::GlobalPaymentMethodId) -> String {
+ todo!()
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub struct SavedPMLPaymentsInfo {
+ pub payment_intent: storage::PaymentIntent,
+ pub business_profile: Option<domain::BusinessProfile>,
+ pub requires_cvv: bool,
+ pub off_session_payment_flag: bool,
+ pub is_connector_agnostic_mit_enabled: bool,
+}
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 5bbfd8483cd..34c5714e126 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -19,6 +19,10 @@ pub enum PaymentTokenKind {
Permanent,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: Option<String>,
@@ -27,6 +31,14 @@ pub struct CardTokenData {
pub network_token_locker_id: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct CardTokenData {
+ pub payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
+ pub locker_id: Option<String>,
+ pub token: String,
+}
+
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
pub struct PaymentMethodDataWithId {
pub payment_method: Option<enums::PaymentMethod>,
@@ -58,6 +70,10 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
pub fn permanent_card(
payment_method_id: Option<String>,
locker_id: Option<String>,
@@ -72,6 +88,19 @@ impl PaymentTokenData {
})
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ pub fn permanent_card(
+ payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
+ }
+
pub fn temporary_generic(token: String) -> Self {
Self::TemporaryGeneric(GenericTokenData { token })
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 1442f5b8d48..a6f6d7c4c5a 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -129,19 +129,7 @@ impl
domain::PaymentMethod,
),
) -> Self {
- Self {
- merchant_id: item.merchant_id.to_owned(),
- customer_id: item.customer_id.to_owned(),
- payment_method_id: item.get_id().clone(),
- payment_method: item.payment_method,
- payment_method_type: item.payment_method_type,
- payment_method_data: card_details.map(payment_methods::PaymentMethodResponseData::Card),
- recurring_enabled: false,
- metadata: item.metadata,
- created: Some(item.created_at),
- last_used_at: None,
- client_secret: item.client_secret,
- }
+ todo!()
}
}
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index abc30074cda..124417e3355 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -14,6 +14,10 @@ pub struct PaymentMethodStatusUpdateWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow {
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 6a796386777..cadb78944ee 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -437,7 +437,7 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("paymentmethod_{}", self.id)]
+ vec![self.id.get_string_repr()]
}
fn table_name(&self) -> &str {
"PaymentMethod"
| 2024-09-05T09:53:05Z |
## Description
<!-- Describe your changes in detail -->
- Core logic for Payment method create API for v2
- Does not contain global_id (will raise separate PR for 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).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Vault dev is incomplete as of now so cannot test. | 97c8e98a48f514b0ba36b109971dd479ae84861e |
Vault dev is incomplete as of now so cannot test.
| [
"crates/api_models/Cargo.toml",
"crates/api_models/src/events.rs",
"crates/api_models/src/payment_methods.rs",
"crates/common_utils/Cargo.toml",
"crates/common_utils/src/events.rs",
"crates/common_utils/src/id_type.rs",
"crates/common_utils/src/id_type/global_id.rs",
"crates/common_utils/src/id_type/p... | |
juspay/hyperswitch | juspay__hyperswitch-5847 | Bug: [FEATURE] add translation to unified error messages in API response and payout link
### Feature Description
Connector can fail due to numerous reasons and usually returns an error code along with an error message. These error messages are specific to the underlying connectors. However, these errors can be logically categorised under a single error code + message combination. This ensures the errors are better understood across different connectors. Once these errors are unified, they can be translated as well based on the requested locale for both payout APIs and payout links.
### Possible Implementation
1. Obtain a list of all the errors across different payout connectors
2. Form unified codes and messages (push them in GSM table)
3. Form translated messages (push them in GSM table)
4. Whenever an error occurs, `unified_code` and `unified_message` is updated in the payout entry (based on DB lookup in GSM)
5. Whenever the payout is requested, the unified error code and message is translated (based on DB lookup in GSM) for the requested locale and attached in the response / link
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR! | diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index acff517e107..e7dbbcdabe6 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -15207,13 +15207,17 @@
},
"unified_code": {
"type": "string",
- "description": "error code unified across the connectors is received here if there was an error while calling connector",
- "nullable": true
+ "description": "(This field is not live yet)\nError code unified across the connectors is received here in case of errors while calling the underlying connector",
+ "example": "UE_000",
+ "nullable": true,
+ "maxLength": 255
},
"unified_message": {
"type": "string",
- "description": "error message unified across the connectors is received here if there was an error while calling connector",
- "nullable": true
+ "description": "(This field is not live yet)\nError message unified across the connectors is received here in case of errors while calling the underlying connector",
+ "example": "Invalid card details",
+ "nullable": true,
+ "maxLength": 1024
}
}
},
@@ -15727,6 +15731,20 @@
"example": "+1",
"nullable": true,
"maxLength": 255
+ },
+ "unified_code": {
+ "type": "string",
+ "description": "(This field is not live yet)\nError code unified across the connectors is received here in case of errors while calling the underlying connector",
+ "example": "UE_000",
+ "nullable": true,
+ "maxLength": 255
+ },
+ "unified_message": {
+ "type": "string",
+ "description": "(This field is not live yet)\nError message unified across the connectors is received here in case of errors while calling the underlying connector",
+ "example": "Invalid card details",
+ "nullable": true,
+ "maxLength": 1024
}
},
"additionalProperties": false
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 01bb63642be..10771df4ccd 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -5,6 +5,7 @@ use common_utils::{
consts::default_payouts_list_limit,
crypto, id_type, link_utils,
pii::{self, Email},
+ types::{UnifiedCode, UnifiedMessage},
};
use masking::Secret;
use router_derive::FlatStruct;
@@ -383,7 +384,7 @@ pub struct Venmo {
pub telephone_number: Option<Secret<String>>,
}
-#[derive(Debug, ToSchema, Clone, Serialize)]
+#[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)]
#[serde(deny_unknown_fields)]
pub struct PayoutCreateResponse {
/// Unique identifier for the payout. This ensures idempotency for multiple payouts
@@ -535,6 +536,18 @@ pub struct PayoutCreateResponse {
/// Customer's phone country code. _Deprecated: Use customer object instead._
#[schema(deprecated, max_length = 255, example = "+1")]
pub phone_country_code: Option<String>,
+
+ /// (This field is not live yet)
+ /// Error code unified across the connectors is received here in case of errors while calling the underlying connector
+ #[remove_in(PayoutCreateResponse)]
+ #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")]
+ pub unified_code: Option<UnifiedCode>,
+
+ /// (This field is not live yet)
+ /// Error message unified across the connectors is received here in case of errors while calling the underlying connector
+ #[remove_in(PayoutCreateResponse)]
+ #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")]
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(
@@ -568,10 +581,16 @@ pub struct PayoutAttemptResponse {
pub connector_transaction_id: Option<String>,
/// If the payout was cancelled the reason provided here
pub cancellation_reason: Option<String>,
- /// error code unified across the connectors is received here if there was an error while calling connector
- pub unified_code: Option<String>,
- /// error message unified across the connectors is received here if there was an error while calling connector
- pub unified_message: Option<String>,
+ /// (This field is not live yet)
+ /// Error code unified across the connectors is received here in case of errors while calling the underlying connector
+ #[remove_in(PayoutAttemptResponse)]
+ #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")]
+ pub unified_code: Option<UnifiedCode>,
+ /// (This field is not live yet)
+ /// Error message unified across the connectors is received here in case of errors while calling the underlying connector
+ #[remove_in(PayoutAttemptResponse)]
+ #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")]
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(Default, Debug, Clone, Deserialize, ToSchema)]
@@ -819,8 +838,8 @@ pub struct PayoutLinkStatusDetails {
pub session_expiry: PrimitiveDateTime,
pub return_url: Option<url::Url>,
pub status: api_enums::PayoutStatus,
- pub error_code: Option<String>,
- pub error_message: Option<String>,
+ pub error_code: Option<UnifiedCode>,
+ pub error_message: Option<UnifiedMessage>,
#[serde(flatten)]
pub ui_config: link_utils::GenericLinkUiConfigFormData,
pub test_mode: bool,
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 299e70dc4c9..70f00ad9b3f 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -146,3 +146,6 @@ pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";
pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only";
/// Role ID for Internal Admin
pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin";
+
+/// Payout flow identifier used for performing GSM operations
+pub const PAYOUT_FLOW_STR: &str = "payout_flow";
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 7f2f844b03f..6acf5000ced 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -32,7 +32,7 @@ use utoipa::ToSchema;
use crate::{
consts,
- errors::{CustomResult, ParsingError, PercentageError},
+ errors::{CustomResult, ParsingError, PercentageError, ValidationError},
};
/// Represents Percentage Value between 0 and 100 both inclusive
#[derive(Clone, Default, Debug, PartialEq, Serialize)]
@@ -767,3 +767,107 @@ where
self.0.to_sql(out)
}
}
+
+/// Domain type for unified code
+#[derive(
+ Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
+)]
+#[diesel(sql_type = sql_types::Text)]
+pub struct UnifiedCode(pub String);
+
+impl TryFrom<String> for UnifiedCode {
+ type Error = error_stack::Report<ValidationError>;
+ fn try_from(src: String) -> Result<Self, Self::Error> {
+ if src.len() > 255 {
+ Err(report!(ValidationError::InvalidValue {
+ message: "unified_code's length should not exceed 255 characters".to_string()
+ }))
+ } else {
+ Ok(Self(src))
+ }
+ }
+}
+
+impl<DB> Queryable<sql_types::Text, DB> for UnifiedCode
+where
+ DB: Backend,
+ Self: FromSql<sql_types::Text, DB>,
+{
+ type Row = Self;
+
+ fn build(row: Self::Row) -> deserialize::Result<Self> {
+ Ok(row)
+ }
+}
+impl<DB> FromSql<sql_types::Text, DB> for UnifiedCode
+where
+ DB: Backend,
+ String: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
+ let val = String::from_sql(bytes)?;
+ Ok(Self::try_from(val)?)
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for UnifiedCode
+where
+ DB: Backend,
+ String: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
+ self.0.to_sql(out)
+ }
+}
+
+/// Domain type for unified messages
+#[derive(
+ Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
+)]
+#[diesel(sql_type = sql_types::Text)]
+pub struct UnifiedMessage(pub String);
+
+impl TryFrom<String> for UnifiedMessage {
+ type Error = error_stack::Report<ValidationError>;
+ fn try_from(src: String) -> Result<Self, Self::Error> {
+ if src.len() > 1024 {
+ Err(report!(ValidationError::InvalidValue {
+ message: "unified_message's length should not exceed 1024 characters".to_string()
+ }))
+ } else {
+ Ok(Self(src))
+ }
+ }
+}
+
+impl<DB> Queryable<sql_types::Text, DB> for UnifiedMessage
+where
+ DB: Backend,
+ Self: FromSql<sql_types::Text, DB>,
+{
+ type Row = Self;
+
+ fn build(row: Self::Row) -> deserialize::Result<Self> {
+ Ok(row)
+ }
+}
+impl<DB> FromSql<sql_types::Text, DB> for UnifiedMessage
+where
+ DB: Backend,
+ String: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
+ let val = String::from_sql(bytes)?;
+ Ok(Self::try_from(val)?)
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for UnifiedMessage
+where
+ DB: Backend,
+ String: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
+ self.0.to_sql(out)
+ }
+}
diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs
index 619e694f411..edb60bc1f44 100644
--- a/crates/diesel_models/src/payout_attempt.rs
+++ b/crates/diesel_models/src/payout_attempt.rs
@@ -1,3 +1,4 @@
+use common_utils::types::{UnifiedCode, UnifiedMessage};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -30,6 +31,8 @@ pub struct PayoutAttempt {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(
@@ -66,6 +69,8 @@ pub struct PayoutAttemptNew {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -76,6 +81,8 @@ pub enum PayoutAttemptUpdate {
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
+ unified_code: Option<UnifiedCode>,
+ unified_message: Option<UnifiedMessage>,
},
PayoutTokenUpdate {
payout_token: String,
@@ -110,6 +117,8 @@ pub struct PayoutAttemptUpdateInternal {
pub address_id: Option<String>,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
impl Default for PayoutAttemptUpdateInternal {
@@ -129,6 +138,8 @@ impl Default for PayoutAttemptUpdateInternal {
last_modified_at: common_utils::date_time::now(),
address_id: None,
customer_id: None,
+ unified_code: None,
+ unified_message: None,
}
}
}
@@ -146,12 +157,16 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
} => Self {
connector_payout_id,
status: Some(status),
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
@@ -197,6 +212,8 @@ impl PayoutAttemptUpdate {
address_id,
customer_id,
merchant_connector_id,
+ unified_code,
+ unified_message,
} = self.into();
PayoutAttempt {
payout_token: payout_token.or(source.payout_token),
@@ -213,6 +230,8 @@ impl PayoutAttemptUpdate {
address_id: address_id.or(source.address_id),
customer_id: customer_id.or(source.customer_id),
merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id),
+ unified_code: unified_code.or(source.unified_code),
+ unified_message: unified_message.or(source.unified_message),
..source
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 6e8918f02a4..b98b19abb46 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1047,6 +1047,10 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
+ #[max_length = 255]
+ unified_code -> Nullable<Varchar>,
+ #[max_length = 1024]
+ unified_message -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index bd64c4bb002..2e007a14840 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1003,6 +1003,10 @@ diesel::table! {
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
routing_info -> Nullable<Jsonb>,
+ #[max_length = 255]
+ unified_code -> Nullable<Varchar>,
+ #[max_length = 1024]
+ unified_message -> Nullable<Varchar>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index f747eb96c4a..9c516142844 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -1,6 +1,9 @@
use api_models::enums::PayoutConnectors;
use common_enums as storage_enums;
-use common_utils::id_type;
+use common_utils::{
+ id_type,
+ types::{UnifiedCode, UnifiedMessage},
+};
use serde::{Deserialize, Serialize};
use storage_enums::MerchantStorageScheme;
use time::PrimitiveDateTime;
@@ -78,6 +81,8 @@ pub struct PayoutAttempt {
pub profile_id: id_type::ProfileId,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(Clone, Debug, PartialEq)]
@@ -101,6 +106,8 @@ pub struct PayoutAttemptNew {
pub profile_id: id_type::ProfileId,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
#[derive(Debug, Clone)]
@@ -111,6 +118,9 @@ pub enum PayoutAttemptUpdate {
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
+
+ unified_code: Option<UnifiedCode>,
+ unified_message: Option<UnifiedMessage>,
},
PayoutTokenUpdate {
payout_token: String,
@@ -143,6 +153,8 @@ pub struct PayoutAttemptUpdateInternal {
pub address_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
+ pub unified_code: Option<UnifiedCode>,
+ pub unified_message: Option<UnifiedMessage>,
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
@@ -158,12 +170,16 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
} => Self {
connector_payout_id,
status: Some(status),
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
diff --git a/crates/router/src/connector/adyenplatform/transformers/payouts.rs b/crates/router/src/connector/adyenplatform/transformers/payouts.rs
index e0ec8f9e18b..09772fc87de 100644
--- a/crates/router/src/connector/adyenplatform/transformers/payouts.rs
+++ b/crates/router/src/connector/adyenplatform/transformers/payouts.rs
@@ -270,14 +270,20 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenTransferResponse>>
item: types::PayoutsResponseRouterData<F, AdyenTransferResponse>,
) -> Result<Self, Self::Error> {
let response: AdyenTransferResponse = item.response;
+ let status = enums::PayoutStatus::from(response.status);
+
+ let error_code = match status {
+ enums::PayoutStatus::Ineligible => Some(response.reason),
+ _ => None,
+ };
Ok(Self {
response: Ok(types::PayoutsResponseData {
- status: Some(enums::PayoutStatus::from(response.status)),
+ status: Some(status),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
- error_code: None,
+ error_code,
error_message: None,
}),
..item.data
diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js
index 473af49b2e7..819d7e63c37 100644
--- a/crates/router/src/core/generic_link/payout_link/status/script.js
+++ b/crates/router/src/core/generic_link/payout_link/status/script.js
@@ -121,10 +121,10 @@ function renderStatusDetails(payoutDetails) {
"{{i18n_ref_id_text}}": payoutDetails.payout_id,
};
if (typeof payoutDetails.error_code === "string") {
- // resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code;
+ resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code;
}
if (typeof payoutDetails.error_message === "string") {
- // resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message;
+ resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message;
}
var resourceNode = document.createElement("div");
resourceNode.id = "resource-info-container";
diff --git a/crates/router/src/core/generic_link/payout_link/status/styles.css b/crates/router/src/core/generic_link/payout_link/status/styles.css
index a10bfe7e3c0..11c6e68dc41 100644
--- a/crates/router/src/core/generic_link/payout_link/status/styles.css
+++ b/crates/router/src/core/generic_link/payout_link/status/styles.css
@@ -80,11 +80,12 @@ body {
#resource-info-container {
width: 100%;
border-top: 1px solid rgb(231, 234, 241);
- padding: 20px 10px;
+ padding: 20px 0;
}
#resource-info {
display: flex;
align-items: center;
+ margin: 0 2.5rem;
}
#info-key {
text-align: right;
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index a153d071088..b175c8b7c03 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -17,7 +17,10 @@ use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use super::errors::{RouterResponse, StorageErrorExt};
use crate::{
configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters},
- core::{payments::helpers, payouts::validator},
+ core::{
+ payments::helpers as payment_helpers,
+ payouts::{helpers as payout_helpers, validator},
+ },
errors,
routes::{app::StorageInterface, SessionState},
services,
@@ -271,6 +274,14 @@ pub async fn initiate_payout_link(
// Send back status page
(_, link_utils::PayoutLinkStatus::Submitted) => {
+ let translated_unified_message =
+ payout_helpers::get_translated_unified_code_and_message(
+ &state,
+ payout_attempt.unified_code.as_ref(),
+ payout_attempt.unified_message.as_ref(),
+ &locale,
+ )
+ .await?;
let js_data = payouts::PayoutLinkStatusDetails {
payout_link_id: payout_link.link_id,
payout_id: payout_link.primary_reference,
@@ -284,8 +295,8 @@ pub async fn initiate_payout_link(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout status link's return URL")?,
status: payout.status,
- error_code: payout_attempt.error_code,
- error_message: payout_attempt.error_message,
+ error_code: payout_attempt.unified_code,
+ error_message: translated_unified_message,
ui_config: ui_config_data,
test_mode: link_data.test_mode.unwrap_or(false),
};
@@ -338,7 +349,7 @@ pub async fn filter_payout_methods(
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// Filter MCAs based on profile_id and connector_type
- let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type(
+ let filtered_mcas = payment_helpers::filter_mca_based_on_profile_and_connector_type(
all_mcas,
&payout.profile_id,
common_enums::ConnectorType::PayoutProcessor,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 85d5b78521f..d0c0b2d3cde 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -16,7 +16,7 @@ use common_utils::{
ext_traits::{AsyncExt, ValueExt},
id_type::CustomerId,
link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus},
- types::MinorUnit,
+ types::{MinorUnit, UnifiedCode, UnifiedMessage},
};
use diesel_models::{
enums as storage_enums,
@@ -71,6 +71,7 @@ pub struct PayoutData {
pub profile_id: common_utils::id_type::ProfileId,
pub should_terminate: bool,
pub payout_link: Option<PayoutLink>,
+ pub current_locale: String,
}
// ********************************************** CORE FLOWS **********************************************
@@ -358,7 +359,7 @@ pub async fn payouts_create_core(
.await?
};
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
#[instrument(skip_all)]
@@ -367,6 +368,7 @@ pub async fn payouts_confirm_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
+ locale: &str,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
@@ -374,6 +376,7 @@ pub async fn payouts_confirm_core(
None,
&key_store,
&payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),
+ locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
@@ -429,7 +432,7 @@ pub async fn payouts_confirm_core(
)
.await?;
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
pub async fn payouts_update_core(
@@ -437,6 +440,7 @@ pub async fn payouts_update_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
+ locale: &str,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let payout_id = req.payout_id.clone().get_required_value("payout_id")?;
let mut payout_data = make_payout_data(
@@ -445,6 +449,7 @@ pub async fn payouts_update_core(
None,
&key_store,
&payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),
+ locale,
)
.await?;
@@ -509,7 +514,7 @@ pub async fn payouts_update_core(
.await?;
}
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
#[instrument(skip_all)]
@@ -519,6 +524,7 @@ pub async fn payouts_retrieve_core(
profile_id: Option<common_utils::id_type::ProfileId>,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutRetrieveRequest,
+ locale: &str,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
@@ -526,6 +532,7 @@ pub async fn payouts_retrieve_core(
profile_id,
&key_store,
&payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()),
+ locale,
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
@@ -553,7 +560,7 @@ pub async fn payouts_retrieve_core(
.await?;
}
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
#[instrument(skip_all)]
@@ -562,6 +569,7 @@ pub async fn payouts_cancel_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutActionRequest,
+ locale: &str,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
@@ -569,6 +577,7 @@ pub async fn payouts_cancel_core(
None,
&key_store,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
+ locale,
)
.await?;
@@ -593,6 +602,8 @@ pub async fn payouts_cancel_core(
error_message: Some("Cancelled by user".to_string()),
error_code: None,
is_eligible: None,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = state
.store
@@ -643,7 +654,7 @@ pub async fn payouts_cancel_core(
.attach_printable("Payout cancellation failed for given Payout request")?;
}
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
#[instrument(skip_all)]
@@ -652,6 +663,7 @@ pub async fn payouts_fulfill_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutActionRequest,
+ locale: &str,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = make_payout_data(
&state,
@@ -659,6 +671,7 @@ pub async fn payouts_fulfill_core(
None,
&key_store,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
+ locale,
)
.await?;
@@ -735,7 +748,7 @@ pub async fn payouts_fulfill_core(
}));
}
- response_handler(&merchant_account, &payout_data).await
+ response_handler(&state, &merchant_account, &payout_data).await
}
#[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))]
@@ -745,6 +758,7 @@ pub async fn payouts_list_core(
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_key_store: domain::MerchantKeyStore,
_constraints: payouts::PayoutListConstraints,
+ _locale: &str,
) -> RouterResponse<payouts::PayoutListResponse> {
todo!()
}
@@ -760,6 +774,7 @@ pub async fn payouts_list_core(
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
constraints: payouts::PayoutListConstraints,
+ _locale: &str,
) -> RouterResponse<payouts::PayoutListResponse> {
validator::validate_payout_list_request(&constraints)?;
let merchant_id = merchant_account.get_id();
@@ -878,6 +893,7 @@ pub async fn payouts_filtered_list_core(
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
filters: payouts::PayoutListFilterConstraints,
+ _locale: &str,
) -> RouterResponse<payouts::PayoutListResponse> {
let limit = &filters.limit;
validator::validate_payout_list_request_for_joins(*limit)?;
@@ -981,6 +997,7 @@ pub async fn payouts_list_available_filters_core(
merchant_account: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: api::TimeRange,
+ _locale: &str,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
let payouts = db
@@ -1293,6 +1310,8 @@ pub async fn create_recipient(
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1406,6 +1425,8 @@ pub async fn check_payout_eligibility(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1437,12 +1458,34 @@ pub async fn check_payout_eligibility(
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
+ let (error_code, error_message) = (Some(err.code), Some(err.message));
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
- error_code: Some(err.code),
- error_message: Some(err.message),
+ error_code,
+ error_message,
is_eligible: Some(false),
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1497,6 +1540,8 @@ pub async fn complete_create_payout(
error_code: None,
error_message: None,
is_eligible: None,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1591,6 +1636,8 @@ pub async fn create_payout(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1622,12 +1669,34 @@ pub async fn create_payout(
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
+ let (error_code, error_message) = (Some(err.code), Some(err.message));
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
- error_code: Some(err.code),
- error_message: Some(err.message),
+ error_code,
+ error_message,
is_eligible: None,
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1774,12 +1843,37 @@ pub async fn update_retrieve_payout_tracker<F, T>(
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = if helpers::is_payout_err_state(status) {
+ let (error_code, error_message) = (
+ payout_response_data.error_code.clone(),
+ payout_response_data.error_message.clone(),
+ );
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
- error_code: payout_response_data.error_code.clone(),
- error_message: payout_response_data.error_message.clone(),
+ error_code,
+ error_message,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
@@ -1788,6 +1882,8 @@ pub async fn update_retrieve_payout_tracker<F, T>(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
}
};
@@ -1886,6 +1982,8 @@ pub async fn create_recipient_disburse_account(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1899,12 +1997,34 @@ pub async fn create_recipient_disburse_account(
.attach_printable("Error updating payout_attempt in db")?;
}
Err(err) => {
+ let (error_code, error_message) = (Some(err.code), Some(err.message));
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status: storage_enums::PayoutStatus::Failed,
- error_code: Some(err.code),
- error_message: Some(err.message),
+ error_code,
+ error_message,
is_eligible: None,
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1964,6 +2084,8 @@ pub async fn cancel_payout(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -1988,12 +2110,34 @@ pub async fn cancel_payout(
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
+ let (error_code, error_message) = (Some(err.code), Some(err.message));
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
- error_code: Some(err.code),
- error_message: Some(err.message),
+ error_code,
+ error_message,
is_eligible: None,
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2075,6 +2219,8 @@ pub async fn fulfill_payout(
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2131,12 +2277,34 @@ pub async fn fulfill_payout(
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
+ let (error_code, error_message) = (Some(err.code), Some(err.message));
+ let (unified_code, unified_message) = helpers::get_gsm_record(
+ state,
+ error_code.clone(),
+ error_message.clone(),
+ payout_data.payout_attempt.connector.clone(),
+ consts::PAYOUT_FLOW_STR,
+ )
+ .await
+ .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message));
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
- error_code: Some(err.code),
- error_message: Some(err.message),
+ error_code,
+ error_message,
is_eligible: None,
+ unified_code: unified_code
+ .map(UnifiedCode::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_code",
+ })?,
+ unified_message: unified_message
+ .map(UnifiedMessage::try_from)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?,
};
payout_data.payout_attempt = db
.update_payout_attempt(
@@ -2165,6 +2333,7 @@ pub async fn fulfill_payout(
}
pub async fn response_handler(
+ state: &SessionState,
merchant_account: &domain::MerchantAccount,
payout_data: &PayoutData,
) -> RouterResponse<payouts::PayoutCreateResponse> {
@@ -2176,12 +2345,20 @@ pub async fn response_handler(
let customer_id = payouts.customer_id;
let billing = billing_address.as_ref().map(From::from);
+ let translated_unified_message = helpers::get_translated_unified_code_and_message(
+ state,
+ payout_attempt.unified_code.as_ref(),
+ payout_attempt.unified_message.as_ref(),
+ &payout_data.current_locale,
+ )
+ .await?;
+
let response = api::PayoutCreateResponse {
payout_id: payouts.payout_id.to_owned(),
merchant_id: merchant_account.get_id().to_owned(),
amount: payouts.amount,
currency: payouts.destination_currency.to_owned(),
- connector: payout_attempt.connector.to_owned(),
+ connector: payout_attempt.connector,
payout_type: payouts.payout_type.to_owned(),
billing,
auto_fulfill: payouts.auto_fulfill,
@@ -2212,6 +2389,8 @@ pub async fn response_handler(
connector_transaction_id: payout_attempt.connector_payout_id,
priority: payouts.priority,
attempts: None,
+ unified_code: payout_attempt.unified_code,
+ unified_message: translated_unified_message,
payout_link: payout_link
.map(|payout_link| {
url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse {
@@ -2389,6 +2568,8 @@ pub async fn payout_create_db_entries(
last_modified_at: common_utils::date_time::now(),
merchant_connector_id: None,
routing_info: None,
+ unified_code: None,
+ unified_message: None,
};
let payout_attempt = db
.insert_payout_attempt(
@@ -2418,6 +2599,7 @@ pub async fn payout_create_db_entries(
should_terminate: false,
profile_id: profile_id.to_owned(),
payout_link,
+ current_locale: locale.to_string(),
})
}
@@ -2428,6 +2610,7 @@ pub async fn make_payout_data(
_auth_profile_id: Option<common_utils::id_type::ProfileId>,
_key_store: &domain::MerchantKeyStore,
_req: &payouts::PayoutRequest,
+ locale: &str,
) -> RouterResult<PayoutData> {
todo!()
}
@@ -2439,6 +2622,7 @@ pub async fn make_payout_data(
auth_profile_id: Option<common_utils::id_type::ProfileId>,
key_store: &domain::MerchantKeyStore,
req: &payouts::PayoutRequest,
+ locale: &str,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_account.get_id();
@@ -2594,6 +2778,7 @@ pub async fn make_payout_data(
should_terminate: false,
profile_id,
payout_link,
+ current_locale: locale.to_string(),
})
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 11cb0c11761..b6f685ee2a1 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -8,7 +8,7 @@ use common_utils::{
fp_utils, id_type, type_name,
types::{
keymanager::{Identifier, KeyManagerState},
- MinorUnit,
+ MinorUnit, UnifiedCode, UnifiedMessage,
},
};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
@@ -944,12 +944,13 @@ pub async fn get_gsm_record(
error_code: Option<String>,
error_message: Option<String>,
connector_name: Option<String>,
- flow: String,
+ flow: &str,
) -> Option<storage::gsm::GatewayStatusMap> {
+ let connector_name = connector_name.unwrap_or_default();
let get_gsm = || async {
state.store.find_gsm_rule(
- connector_name.clone().unwrap_or_default(),
- flow.clone(),
+ connector_name.clone(),
+ flow.to_string(),
"sub_flow".to_string(),
error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
error_message.clone().unwrap_or_default(),
@@ -959,7 +960,7 @@ pub async fn get_gsm_record(
if err.current_context().is_db_not_found() {
logger::warn!(
"GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
- connector_name.unwrap_or_default(),
+ connector_name,
flow,
error_code,
error_message
@@ -1265,3 +1266,29 @@ pub(super) fn get_customer_details_from_request(
phone_country_code: customer_phone_code,
}
}
+
+pub async fn get_translated_unified_code_and_message(
+ state: &SessionState,
+ unified_code: Option<&UnifiedCode>,
+ unified_message: Option<&UnifiedMessage>,
+ locale: &str,
+) -> CustomResult<Option<UnifiedMessage>, errors::ApiErrorResponse> {
+ Ok(unified_code
+ .zip(unified_message)
+ .async_and_then(|(code, message)| async {
+ payment_helpers::get_unified_translation(
+ state,
+ code.0.clone(),
+ message.0.clone(),
+ locale.to_string(),
+ )
+ .await
+ .map(UnifiedMessage::try_from)
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "unified_message",
+ })?
+ .or_else(|| unified_message.cloned()))
+}
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index e190e627bdf..00c25b0d67e 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -190,12 +190,15 @@ pub async fn get_gsm(
let error_code = payout_data.payout_attempt.error_code.to_owned();
let error_message = payout_data.payout_attempt.error_message.to_owned();
let connector_name = Some(original_connector_data.connector_name.to_string());
- let flow = "payout_flow".to_string();
- Ok(
- payouts::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow)
- .await,
+ Ok(payouts::helpers::get_gsm_record(
+ state,
+ error_code,
+ error_message,
+ connector_name,
+ common_utils::consts::PAYOUT_FLOW_STR,
)
+ .await)
}
#[instrument(skip_all)]
@@ -295,6 +298,8 @@ pub async fn modify_trackers(
last_modified_at: common_utils::date_time::now(),
merchant_connector_id: None,
routing_info: None,
+ unified_code: None,
+ unified_message: None,
};
payout_data.payout_attempt = db
.insert_payout_attempt(
diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs
index ed17eb71afa..080cf775b24 100644
--- a/crates/router/src/core/payouts/transformers.rs
+++ b/crates/router/src/core/payouts/transformers.rs
@@ -98,10 +98,12 @@ impl
created: Some(payout.created_at),
connector_transaction_id: attempt.connector_transaction_id.clone(),
priority: payout.priority,
- attempts: Some(vec![attempt]),
billing: address,
client_secret: None,
payout_link: None,
+ unified_code: attempt.unified_code.clone(),
+ unified_message: attempt.unified_message.clone(),
+ attempts: Some(vec![attempt]),
email: customer
.as_ref()
.and_then(|customer| customer.email.clone()),
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 20b07d8669f..dd7ccd87f38 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -689,6 +689,8 @@ async fn payouts_incoming_webhook_flow(
error_message: None,
error_code: None,
is_eligible: payout_attempt.is_eligible,
+ unified_code: None,
+ unified_message: None,
};
let action_req =
@@ -696,9 +698,15 @@ async fn payouts_incoming_webhook_flow(
payout_id: payouts.payout_id.clone(),
});
- let payout_data =
- payouts::make_payout_data(&state, &merchant_account, None, &key_store, &action_req)
- .await?;
+ let payout_data = payouts::make_payout_data(
+ &state,
+ &merchant_account,
+ None,
+ &key_store,
+ &action_req,
+ common_utils::consts::DEFAULT_LOCALE,
+ )
+ .await?;
let updated_payout_attempt = db
.update_payout_attempt(
@@ -721,7 +729,7 @@ async fn payouts_incoming_webhook_flow(
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let router_response =
- payouts::response_handler(&merchant_account, &payout_data).await?;
+ payouts::response_handler(&state, &merchant_account, &payout_data).await?;
let payout_create_response: payout_models::PayoutCreateResponse = match router_response
{
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 50c18d71f2a..1b614330ebd 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -1,5 +1,6 @@
use actix_web::{
body::{BoxBody, MessageBody},
+ http::header::HeaderMap,
web, HttpRequest, HttpResponse, Responder,
};
use common_enums::EntityType;
@@ -20,6 +21,14 @@ use crate::{
types::api::payouts as payout_types,
};
+fn get_locale_from_header(headers: &HeaderMap) -> String {
+ get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)
+ .ok()
+ .flatten()
+ .map(|val| val.to_string())
+ .unwrap_or(consts::DEFAULT_LOCALE.to_string())
+}
+
/// Payouts - Create
#[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))]
pub async fn payouts_create(
@@ -28,11 +37,8 @@ pub async fn payouts_create(
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsCreate;
- let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), req.headers())
- .ok()
- .flatten()
- .map(|val| val.to_string())
- .unwrap_or(consts::DEFAULT_LOCALE.to_string());
+ let locale = get_locale_from_header(req.headers());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -60,6 +66,8 @@ pub async fn payouts_retrieve(
merchant_id: query_params.merchant_id.to_owned(),
};
let flow = Flow::PayoutsRetrieve;
+ let locale = get_locale_from_header(req.headers());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -72,6 +80,7 @@ pub async fn payouts_retrieve(
auth.profile_id,
auth.key_store,
req,
+ &locale,
)
},
auth::auth_type(
@@ -95,6 +104,7 @@ pub async fn payouts_update(
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsUpdate;
+ let locale = get_locale_from_header(req.headers());
let payout_id = path.into_inner();
let mut payout_update_payload = json_payload.into_inner();
payout_update_payload.payout_id = Some(payout_id);
@@ -104,7 +114,7 @@ pub async fn payouts_update(
&req,
payout_update_payload,
|state, auth, req, _| {
- payouts_update_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_update_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
@@ -130,6 +140,7 @@ pub async fn payouts_confirm(
Ok(auth) => auth,
Err(e) => return api::log_and_return_error_response(e),
};
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -137,7 +148,7 @@ pub async fn payouts_confirm(
&req,
payload,
|state, auth, req, _| {
- payouts_confirm_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_confirm_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
@@ -156,6 +167,7 @@ pub async fn payouts_cancel(
let flow = Flow::PayoutsCancel;
let mut payload = json_payload.into_inner();
payload.payout_id = path.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -163,7 +175,7 @@ pub async fn payouts_cancel(
&req,
payload,
|state, auth, req, _| {
- payouts_cancel_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_cancel_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
@@ -181,6 +193,7 @@ pub async fn payouts_fulfill(
let flow = Flow::PayoutsFulfill;
let mut payload = json_payload.into_inner();
payload.payout_id = path.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -188,7 +201,7 @@ pub async fn payouts_fulfill(
&req,
payload,
|state, auth, req, _| {
- payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
@@ -206,6 +219,7 @@ pub async fn payouts_list(
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -213,7 +227,14 @@ pub async fn payouts_list(
&req,
payload,
|state, auth, req, _| {
- payouts_list_core(state, auth.merchant_account, None, auth.key_store, req)
+ payouts_list_core(
+ state,
+ auth.merchant_account,
+ None,
+ auth.key_store,
+ req,
+ &locale,
+ )
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
@@ -238,6 +259,7 @@ pub async fn payouts_list_profile(
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -251,6 +273,7 @@ pub async fn payouts_list_profile(
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
+ &locale,
)
},
auth::auth_type(
@@ -276,6 +299,7 @@ pub async fn payouts_list_by_filter(
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -283,7 +307,14 @@ pub async fn payouts_list_by_filter(
&req,
payload,
|state, auth, req, _| {
- payouts_filtered_list_core(state, auth.merchant_account, None, auth.key_store, req)
+ payouts_filtered_list_core(
+ state,
+ auth.merchant_account,
+ None,
+ auth.key_store,
+ req,
+ &locale,
+ )
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
@@ -308,6 +339,7 @@ pub async fn payouts_list_by_filter_profile(
) -> HttpResponse {
let flow = Flow::PayoutsList;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -321,6 +353,7 @@ pub async fn payouts_list_by_filter_profile(
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
+ &locale,
)
},
auth::auth_type(
@@ -346,6 +379,7 @@ pub async fn payouts_list_available_filters_for_merchant(
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -353,7 +387,7 @@ pub async fn payouts_list_available_filters_for_merchant(
&req,
payload,
|state, auth, req, _| {
- payouts_list_available_filters_core(state, auth.merchant_account, None, req)
+ payouts_list_available_filters_core(state, auth.merchant_account, None, req, &locale)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
@@ -378,6 +412,7 @@ pub async fn payouts_list_available_filters_for_profile(
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
+ let locale = get_locale_from_header(req.headers());
Box::pin(api::server_wrap(
flow,
@@ -390,6 +425,7 @@ pub async fn payouts_list_available_filters_for_profile(
auth.merchant_account,
auth.profile_id.map(|profile_id| vec![profile_id]),
req,
+ &locale,
)
},
auth::auth_type(
diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs
index fa481fdb9d6..b29a15725b0 100644
--- a/crates/router/src/workflows/attach_payout_account_workflow.rs
+++ b/crates/router/src/workflows/attach_payout_account_workflow.rs
@@ -1,4 +1,7 @@
-use common_utils::ext_traits::{OptionExt, ValueExt};
+use common_utils::{
+ consts::DEFAULT_LOCALE,
+ ext_traits::{OptionExt, ValueExt},
+};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
@@ -46,8 +49,15 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {
let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data);
- let mut payout_data =
- payouts::make_payout_data(state, &merchant_account, None, &key_store, &request).await?;
+ let mut payout_data = payouts::make_payout_data(
+ state,
+ &merchant_account,
+ None,
+ &key_store,
+ &request,
+ DEFAULT_LOCALE,
+ )
+ .await?;
payouts::payouts_core(
state,
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index 138b1477d6a..e29277caf4e 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -5,7 +5,10 @@ use api_models::{
webhook_events::OutgoingWebhookRequestContent,
webhooks::{OutgoingWebhook, OutgoingWebhookContent},
};
-use common_utils::ext_traits::{StringExt, ValueExt};
+use common_utils::{
+ consts::DEFAULT_LOCALE,
+ ext_traits::{StringExt, ValueExt},
+};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use masking::PeekInterface;
@@ -521,12 +524,18 @@ async fn get_outgoing_webhook_content_and_event_type(
payout_models::PayoutActionRequest { payout_id },
);
- let payout_data =
- payouts::make_payout_data(&state, &merchant_account, None, &key_store, &request)
- .await?;
+ let payout_data = payouts::make_payout_data(
+ &state,
+ &merchant_account,
+ None,
+ &key_store,
+ &request,
+ DEFAULT_LOCALE,
+ )
+ .await?;
let router_response =
- payouts::response_handler(&merchant_account, &payout_data).await?;
+ payouts::response_handler(&state, &merchant_account, &payout_data).await?;
let payout_create_response: payout_models::PayoutCreateResponse = match router_response
{
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 697b5d91c93..e5bfe29af54 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -84,6 +84,8 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
profile_id: new_payout_attempt.profile_id.clone(),
merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(),
routing_info: new_payout_attempt.routing_info.clone(),
+ unified_code: new_payout_attempt.unified_code.clone(),
+ unified_message: new_payout_attempt.unified_message.clone(),
};
let redis_entry = kv::TypedSql {
@@ -525,6 +527,8 @@ impl DataModelExt for PayoutAttempt {
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
+ unified_code: self.unified_code,
+ unified_message: self.unified_message,
}
}
@@ -549,6 +553,8 @@ impl DataModelExt for PayoutAttempt {
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
+ unified_code: storage_model.unified_code,
+ unified_message: storage_model.unified_message,
}
}
}
@@ -576,6 +582,8 @@ impl DataModelExt for PayoutAttemptNew {
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
+ unified_code: self.unified_code,
+ unified_message: self.unified_message,
}
}
@@ -600,6 +608,8 @@ impl DataModelExt for PayoutAttemptNew {
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
+ unified_code: storage_model.unified_code,
+ unified_message: storage_model.unified_message,
}
}
}
@@ -613,12 +623,16 @@ impl DataModelExt for PayoutAttemptUpdate {
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
} => DieselPayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
+ unified_code,
+ unified_message,
},
Self::PayoutTokenUpdate { payout_token } => {
DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token }
diff --git a/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql
new file mode 100644
index 00000000000..b785cad78fb
--- /dev/null
+++ b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql
@@ -0,0 +1,3 @@
+ALTER TABLE payout_attempt
+DROP COLUMN IF EXISTS unified_code,
+DROP COLUMN IF EXISTS unified_message;
\ No newline at end of file
diff --git a/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql
new file mode 100644
index 00000000000..b4ccfb8e525
--- /dev/null
+++ b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql
@@ -0,0 +1,3 @@
+ALTER TABLE payout_attempt
+ADD COLUMN IF NOT EXISTS unified_code VARCHAR(255) DEFAULT NULL,
+ADD COLUMN IF NOT EXISTS unified_message VARCHAR(1024) DEFAULT NULL;
\ No newline at end of file
| 2024-09-05T09:45:42Z |
## Description
This adds `unified_code` and `unified_message` in the payout's API response. These values are looked up in the DB and populated in the API response.
`unified_code` and `unified_message` are then used to fetch the translated message string from DB (if present). This is finally returned in the payouts API response and / or embedded in the payout link.
### Additional Changes
- [x] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
**Pre-requisites**
1. Ensure payout unified code and messages are inserted in `gateway_status_map` table
2. Ensure the translated messages for these unified code <> messages are inserted in `unified_translations` table
<details>
<summary>1. Create an invalid payout txn</summary>
cURL
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"description": "Its my first payout request",
"payout_type": "bank",
"priority": "instant",
"payout_method_data": {
"bank": {
"iban": "ES6614657716831375381753"
}
},
"connector": [
"adyenplatform"
],
"billing": {
"address": {
"line1": "Raadhuisplein",
"line2": "92",
"city": "Hoogeveen",
"state": "FL",
"zip": "7901 BW",
"country": "DE",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true,
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp"
}'
Response with unified code and message
{
"payout_id": "d0ed3417-5f1f-46ad-8535-f02f2a8c96cf",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_d0ed3417-5f1f-46ad-8535-f02f2a8c96cf_secret_xlTRh9qeyr6Y5tb7flCn",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:37:00.616Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Invalid recipient details"
}
</details>
<details>
<summary>2. Create an invalid payout txn with language in the header</summary>
cURL
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"description": "Its my first payout request",
"payout_type": "bank",
"priority": "instant",
"payout_method_data": {
"bank": {
"iban": "ES6614657716831375381753"
}
},
"connector": [
"adyenplatform"
],
"billing": {
"address": {
"line1": "Raadhuisplein",
"line2": "92",
"city": "Hoogeveen",
"state": "FL",
"zip": "7901 BW",
"country": "DE",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true,
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp"
}'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Détails du destinataire invalides"
}
</details>
<details>
<summary>3. List this payout in different languages</summary>
cURL (ENGLISH)
curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \
--header 'Accept-Language: en' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Invalid recipient details"
}
cURL (nl)
curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \
--header 'Accept-Language: nl' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Ongeldige ontvangersgegevens"
}
</details>
<details>
<summary>4. Submit invalid details in payout details, and open status page</summary>
English

French

</details> | 2aa215440e0531e315e61ee30bbbc5a5685481b3 | **Pre-requisites**
1. Ensure payout unified code and messages are inserted in `gateway_status_map` table
2. Ensure the translated messages for these unified code <> messages are inserted in `unified_translations` table
<details>
<summary>1. Create an invalid payout txn</summary>
cURL
curl --location 'http://localhost:8080/payouts/create' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"description": "Its my first payout request",
"payout_type": "bank",
"priority": "instant",
"payout_method_data": {
"bank": {
"iban": "ES6614657716831375381753"
}
},
"connector": [
"adyenplatform"
],
"billing": {
"address": {
"line1": "Raadhuisplein",
"line2": "92",
"city": "Hoogeveen",
"state": "FL",
"zip": "7901 BW",
"country": "DE",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true,
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp"
}'
Response with unified code and message
{
"payout_id": "d0ed3417-5f1f-46ad-8535-f02f2a8c96cf",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_d0ed3417-5f1f-46ad-8535-f02f2a8c96cf_secret_xlTRh9qeyr6Y5tb7flCn",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:37:00.616Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Invalid recipient details"
}
</details>
<details>
<summary>2. Create an invalid payout txn with language in the header</summary>
cURL
curl --location 'http://localhost:8080/payouts/create' \
--header 'Accept-Language: fr' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \
--data '{
"amount": 1,
"currency": "EUR",
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"description": "Its my first payout request",
"payout_type": "bank",
"priority": "instant",
"payout_method_data": {
"bank": {
"iban": "ES6614657716831375381753"
}
},
"connector": [
"adyenplatform"
],
"billing": {
"address": {
"line1": "Raadhuisplein",
"line2": "92",
"city": "Hoogeveen",
"state": "FL",
"zip": "7901 BW",
"country": "DE",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
}
},
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"confirm": true,
"auto_fulfill": true,
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp"
}'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Détails du destinataire invalides"
}
</details>
<details>
<summary>3. List this payout in different languages</summary>
cURL (ENGLISH)
curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \
--header 'Accept-Language: en' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Invalid recipient details"
}
cURL (nl)
curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \
--header 'Accept-Language: nl' \
--header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9'
Response
{
"payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56",
"merchant_id": "merchant_1726461298",
"amount": 1,
"currency": "EUR",
"connector": "adyenplatform",
"payout_type": "bank",
"billing": {
"address": {
"city": "Hoogeveen",
"country": "DE",
"line1": "Raadhuisplein",
"line2": "92",
"line3": null,
"zip": "7901 BW",
"state": "FL",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "0650242319",
"country_code": "+31"
},
"email": null
},
"auto_fulfill": true,
"customer_id": "cus_BF9z0OVpYLybZlkPLdeP",
"customer": {
"id": "cus_BF9z0OVpYLybZlkPLdeP",
"name": "John Doe",
"email": "guest@example.com",
"phone": "6168205366",
"phone_country_code": "+1"
},
"client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H",
"return_url": null,
"business_country": null,
"business_label": null,
"description": "Its my first payout request",
"entity_type": "Individual",
"recurring": true,
"metadata": {
"ref": "123"
},
"merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN",
"status": "failed",
"error_message": "Invalid transfer information provided",
"error_code": "30_081",
"profile_id": "pro_9GxLZ4gAqCxlLOnAndXp",
"created": "2024-09-16T05:43:24.401Z",
"connector_transaction_id": null,
"priority": "instant",
"payout_link": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "6168205366",
"phone_country_code": "+1",
"unified_code": "UE_1200",
"unified_message": "Ongeldige ontvangersgegevens"
}
</details>
<details>
<summary>4. Submit invalid details in payout details, and open status page</summary>
English

French

</details>
| [
"api-reference-v2/openapi_spec.json",
"crates/api_models/src/payouts.rs",
"crates/common_utils/src/consts.rs",
"crates/common_utils/src/types.rs",
"crates/diesel_models/src/payout_attempt.rs",
"crates/diesel_models/src/schema.rs",
"crates/diesel_models/src/schema_v2.rs",
"crates/hyperswitch_domain_mod... | |
juspay/hyperswitch | juspay__hyperswitch-5805 | Bug: feat(payouts): Add profile level get filters API for payouts
Currently payout get filter API gives filters whole merchant. Since dashboard is being moved to profile level, filter API at profile level should be needed. | diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 515a7be959a..65490e2d270 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -947,10 +947,11 @@ pub async fn payouts_filtered_list_core(
pub async fn payouts_list_available_filters_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
+ profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: api::TimeRange,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
- let payout = db
+ let payouts = db
.filter_payouts_by_time_range_constraints(
merchant_account.get_id(),
&time_range,
@@ -959,9 +960,11 @@ pub async fn payouts_list_available_filters_core(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
+
let filters = db
.get_filters_for_payouts(
- payout.as_slice(),
+ payouts.as_slice(),
merchant_account.get_id(),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 8201380cc29..d3b9801cedf 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1021,7 +1021,12 @@ impl Payouts {
.route(web::post().to(payouts_list_by_filter_profile)),
)
.service(
- web::resource("/filter").route(web::post().to(payouts_list_available_filters)),
+ web::resource("/filter")
+ .route(web::post().to(payouts_list_available_filters_for_merchant)),
+ )
+ .service(
+ web::resource("/profile/filter")
+ .route(web::post().to(payouts_list_available_filters_for_profile)),
);
}
route = route
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index bc14a619745..8c45f9fdfd9 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -320,10 +320,10 @@ pub async fn payouts_list_by_filter_profile(
.await
}
-/// Payouts - Available filters
+/// Payouts - Available filters for Merchant
#[cfg(feature = "olap")]
#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
-pub async fn payouts_list_available_filters(
+pub async fn payouts_list_available_filters_for_merchant(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<payment_types::TimeRange>,
@@ -337,7 +337,41 @@ pub async fn payouts_list_available_filters(
&req,
payload,
|state, auth, req, _| {
- payouts_list_available_filters_core(state, auth.merchant_account, req)
+ payouts_list_available_filters_core(state, auth.merchant_account, None, req)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+/// Payouts - Available filters for Profile
+#[cfg(feature = "olap")]
+#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))]
+pub async fn payouts_list_available_filters_for_profile(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_types::TimeRange>,
+) -> HttpResponse {
+ let flow = Flow::PayoutsFilter;
+ let payload = json_payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ payouts_list_available_filters_core(
+ state,
+ auth.merchant_account,
+ auth.profile_id.map(|profile_id| vec![profile_id]),
+ req,
+ )
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
| 2024-09-05T08:25:23Z |
## Description
<!-- Describe your changes in detail -->
- This PR adds a profile level get filters api for payouts.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #5805.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/payouts/profile/filter' \
--header 'Content-Type: application/json' \
--header 'authorization: Bearer JWT with profile_id' \
--data '{"start_time":"2024-08-05T18:30:00Z","end_time":"2024-09-05T08:19:00Z"}'
```
Response will look like this
```json
{
"connector": [],
"currency": [],
"status": [],
"payout_method": []
}
```
This API should only give filters for payouts which have profile_id as the one in JWT.
This cannot be tested in integ/sandbox as the JWT currently doesn't have profile_id. | db04ded4a460abfb073167d59b3c51a4e7972c54 |
```
curl --location 'http://localhost:8080/payouts/profile/filter' \
--header 'Content-Type: application/json' \
--header 'authorization: Bearer JWT with profile_id' \
--data '{"start_time":"2024-08-05T18:30:00Z","end_time":"2024-09-05T08:19:00Z"}'
```
Response will look like this
```json
{
"connector": [],
"currency": [],
"status": [],
"payout_method": []
}
```
This API should only give filters for payouts which have profile_id as the one in JWT.
This cannot be tested in integ/sandbox as the JWT currently doesn't have profile_id.
| [
"crates/router/src/core/payouts.rs",
"crates/router/src/routes/app.rs",
"crates/router/src/routes/payouts.rs"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.