repo
stringclasses 1
value | instance_id
stringlengths 22
24
| problem_statement
stringlengths 24
24.1k
| patch
stringlengths 0
1.9M
| test_patch
stringclasses 1
value | created_at
stringdate 2022-11-25 05:12:07
2025-10-09 08:44:51
| hints_text
stringlengths 11
235k
| base_commit
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|
juspay/hyperswitch
|
juspay__hyperswitch-6609
|
Bug: [FEATURE] align the JSON deserialization errors into expected ErrorResponse format
### Feature Description
HyperSwitch uses an error format for responding back with the errors in the API. This error structure is uniform across different stages of the flow. For any deserialization errors in the API, error response with a different structure is returned.
Expected
```
{
"error": {
"error_type": "invalid_request",
"message": "Json deserialize error: unknown variant `automatiac`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled` at line 5 column 34",
"code": "IR_06"
}
}
```
Actual
```
{
"error": "Json deserialize error: unknown variant `automatiac`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled` at line 5 column 34"
}
```
### Possible Implementation
Update the `Display` implementation of `CustomJsonError`
### 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/utils.rs b/crates/router/src/utils.rs
index 515c9a94ce8..ca61543ec57 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -81,7 +81,11 @@ pub mod error_parser {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(
serde_json::to_string(&serde_json::json!({
- "error": self.err.to_string()
+ "error": {
+ "error_type": "invalid_request",
+ "message": self.err.to_string(),
+ "code": "IR_06",
+ }
}))
.as_deref()
.unwrap_or("Invalid Json Error"),
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
index c2d1b7483c1..d445dbd26cd 100644
--- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
+++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js
@@ -964,7 +964,11 @@ export const connectorDetails = {
Response: {
status: 400,
body: {
- error: "Json deserialize error: invalid card number length",
+ error: {
+ error_type: "invalid_request",
+ message: "Json deserialize error: invalid card number length",
+ code: "IR_06"
+ },
},
},
},
@@ -1068,8 +1072,11 @@ export const connectorDetails = {
Response: {
status: 400,
body: {
- error:
- "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`",
+ error: {
+ error_type: "invalid_request",
+ message: "Json deserialize error: unknown variant `United`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL`",
+ code: "IR_06"
+ },
},
},
},
@@ -1093,8 +1100,11 @@ export const connectorDetails = {
Response: {
status: 400,
body: {
- error:
- "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`",
+ error: {
+ error_type: "invalid_request",
+ message: "Json deserialize error: unknown variant `auto`, expected one of `automatic`, `manual`, `manual_multiple`, `scheduled`",
+ code: "IR_06"
+ },
},
},
},
@@ -1117,8 +1127,11 @@ export const connectorDetails = {
Response: {
status: 400,
body: {
- error:
- "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`",
+ error: {
+ error_type: "invalid_request",
+ message: "Json deserialize error: unknown variant `this_supposed_to_be_a_card`, expected one of `card`, `card_redirect`, `pay_later`, `wallet`, `bank_redirect`, `bank_transfer`, `crypto`, `bank_debit`, `reward`, `real_time_payment`, `upi`, `voucher`, `gift_card`, `open_banking`, `mobile_payment`",
+ code: "IR_06"
+ },
},
},
},
diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js
index 9785839f422..569b557b690 100644
--- a/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js
+++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Utils.js
@@ -88,9 +88,14 @@ export function defaultErrorHandler(response, response_data) {
if (typeof response.body.error === "object") {
for (const key in response_data.body.error) {
- expect(response_data.body.error[key]).to.equal(response.body.error[key]);
+ // Check if the error message is a Json deserialize error
+ let apiResponseContent = response.body.error[key];
+ let expectedContent = response_data.body.error[key];
+ if (typeof apiResponseContent === "string" && apiResponseContent.includes("Json deserialize error")) {
+ expect(apiResponseContent).to.include(expectedContent);
+ } else {
+ expect(apiResponseContent).to.equal(expectedContent);
+ }
}
- } else if (typeof response.body.error === "string") {
- expect(response.body.error).to.include(response_data.body.error);
}
}
|
2024-11-19T11:05:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #6609
### 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?
Locally.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8e9c3ec8931851dae638037b91eb1611399be0bf
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6605
|
Bug: feat(analytics): add first_attempt as a filter for PaymentFilters
Need to add `first_attempt` as a filter in PaymentFilters.
This is required for the new Analytics v2 `Smart Retries Metrics`, specifically S`mart Retries Successful Distribution `and `Smart Retries Failure Distribution`, for calculations only involving smart retries (ignoring first attempts).
|
diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs
index 51805acaae2..668bdaa6c8b 100644
--- a/crates/analytics/src/payments/filters.rs
+++ b/crates/analytics/src/payments/filters.rs
@@ -64,4 +64,5 @@ pub struct PaymentFilterRow {
pub card_last_4: Option<String>,
pub card_issuer: Option<String>,
pub error_reason: Option<String>,
+ pub first_attempt: Option<bool>,
}
diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs
index e23fc6cbbb3..b9af3cd0610 100644
--- a/crates/analytics/src/payments/types.rs
+++ b/crates/analytics/src/payments/types.rs
@@ -104,6 +104,11 @@ where
.add_filter_in_range_clause(PaymentDimensions::ErrorReason, &self.error_reason)
.attach_printable("Error adding error reason filter")?;
}
+ if !self.first_attempt.is_empty() {
+ builder
+ .add_filter_in_range_clause("first_attempt", &self.first_attempt)
+ .attach_printable("Error adding first attempt filter")?;
+ }
Ok(())
}
}
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index d746594e36e..e80f762c41b 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -457,6 +457,12 @@ impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId {
}
}
+impl<T: AnalyticsDataSource> ToSql<T> for bool {
+ fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
+ Ok(self.to_string().to_owned())
+ }
+}
+
/// Implement `ToSql` on arrays of types that impl `ToString`.
macro_rules! impl_to_sql_for_to_string {
($($type:ty),+) => {
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 0a641fbc5f9..16523d5d0a7 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -569,6 +569,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
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),
+ })?;
Ok(Self {
currency,
status,
@@ -584,6 +588,7 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow {
card_last_4,
card_issuer,
error_reason,
+ first_attempt,
})
}
}
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index b34f8c9293c..23d64ff1886 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -41,6 +41,8 @@ pub struct PaymentFilters {
pub card_issuer: Vec<String>,
#[serde(default)]
pub error_reason: Vec<String>,
+ #[serde(default)]
+ pub first_attempt: Vec<bool>,
}
#[derive(
|
2024-11-19T08:32:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added `first_attempt` as a filter in `PaymentFilters`.
This is required for the new Analytics v2 `Smart Retries` Metrics, specifically `Smart Retries Successful Distribution` and `Smart Retries Failure Distribution`, for calculations only involving smart retries (ignoring first attempts).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Helps in calculating certain metrics seamlessly.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Hit the curl:
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \
--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-11-19T00:30:00Z",
"endTime": "2024-11-19T23:30:00Z"
},
"groupByNames": [
"connector"
],
"filters": {
"first_attempt": [false]
},
"source": "BATCH",
"metrics": [
"payments_distribution"
],
"delta": true
}
]'
```
Response body:
```json
{
"queryData": [
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 0,
"payment_processed_amount_in_usd": null,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_amount_without_smart_retries_usd": null,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": 100.0,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_success_rate_distribution_with_only_retries": 100.0,
"payments_failure_rate_distribution": 0.0,
"payments_failure_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution_with_only_retries": 0.0,
"failure_reason_count": 0,
"failure_reason_count_without_smart_retries": 0,
"currency": null,
"status": null,
"connector": "stripe_test",
"authentication_type": null,
"payment_method": null,
"payment_method_type": null,
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": null,
"time_range": {
"start_time": "2024-11-19T00:30:00.000Z",
"end_time": "2024-11-19T23:30:00.000Z"
},
"time_bucket": "2024-11-19 00:30:00"
}
],
"metaData": [
{
"total_payment_processed_amount": 0,
"total_payment_processed_amount_in_usd": 0,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_amount_without_smart_retries_usd": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0,
"total_failure_reasons_count": 0,
"total_failure_reasons_count_without_smart_retries": 0
}
]
}
```
Now this response will only have data related to the attempts which are not the first attempt, and are only subsequent smart rertries.
Fields that can be observed in the `queryData`:
```json
"payments_success_rate_distribution_with_only_retries": 100.0,
"payments_failure_rate_distribution_with_only_retries": 0.0,
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
65bf75a75e1e7d705de3ee3e9080a7a86099ffc3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6600
|
Bug: fix(users): Only use lowercase letters in emails
Currently uppercase letters in emails are being using at it is. Ideally we should convert them to lowercase before performing any DB operations with it.
|
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 5a881728b07..4cb69e68ed8 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -103,7 +103,7 @@ impl UserEmail {
pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> {
use validator::ValidateEmail;
- let email_string = email.expose();
+ let email_string = email.expose().to_lowercase();
let email =
pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?;
@@ -123,21 +123,8 @@ impl UserEmail {
}
pub fn from_pii_email(email: pii::Email) -> UserResult<Self> {
- use validator::ValidateEmail;
-
- let email_string = email.peek();
- if email_string.validate_email() {
- let (_username, domain) = match email_string.split_once('@') {
- Some((u, d)) => (u, d),
- None => return Err(UserErrors::EmailParsingError.into()),
- };
- if BLOCKED_EMAIL.contains(domain) {
- return Err(UserErrors::InvalidEmailError.into());
- }
- Ok(Self(email))
- } else {
- Err(UserErrors::EmailParsingError.into())
- }
+ let email_string = email.expose().map(|inner| inner.to_lowercase());
+ Self::new(email_string)
}
pub fn into_inner(self) -> pii::Email {
|
2024-11-18T13:19:55Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR changes will convert emails from request to lowercase before performing any DB operations.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6600.
## How did you test 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/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "USER@Example.com"
}'
```
This email in the about request will be inserted as `user@example.com` in DB.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
43d87913ab3d177a6d193b3e475c96609cc09a28
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6598
|
Bug: feat(authn): Use cookies for authentication
Currently we use auth headers and local storage in FE for transfer JWT from FE to BE.
Cookies is a better way to do this, as it is handled by browser and JavaScript doesn't have access to.
First we will test this in Integ and slowly move it to sandbox and production.
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 191f2ba7f8b..52b704e1adc 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -403,6 +403,7 @@ two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should
totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP
base_url = "" # Base url used for user specific redirects and emails
force_two_factor_auth = false # Whether to force two factor authentication for all users
+force_cookies = true # Whether to use only cookies for JWT extraction and authentication
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 00a544dc565..0765591c63b 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -145,6 +145,7 @@ two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Integ"
base_url = "https://integ.hyperswitch.io"
force_two_factor_auth = false
+force_cookies = true
[frm]
enabled = true
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 0fe9095d280..d9d3e852d1b 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -152,6 +152,7 @@ two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Production"
base_url = "https://live.hyperswitch.io"
force_two_factor_auth = true
+force_cookies = false
[frm]
enabled = false
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 82c347ae389..b3b57e9d202 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -152,6 +152,7 @@ two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Sandbox"
base_url = "https://app.hyperswitch.io"
force_two_factor_auth = false
+force_cookies = false
[frm]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index ee6ea5dab0b..0c4d92fc519 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -329,6 +329,7 @@ two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Dev"
base_url = "http://localhost:8080"
force_two_factor_auth = false
+force_cookies = true
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index ed0ede98d94..f1d02d30345 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -57,6 +57,7 @@ two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch"
base_url = "http://localhost:8080"
force_two_factor_auth = false
+force_cookies = true
[locker]
host = ""
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7b212ec6d1d..4e559a261b9 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -557,6 +557,7 @@ pub struct UserSettings {
pub totp_issuer_name: String,
pub base_url: String,
pub force_two_factor_auth: bool,
+ pub force_cookies: bool,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f01f6c5d749..c6501dac3bd 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -294,7 +294,7 @@ pub async fn connect_account(
pub async fn signout(
state: SessionState,
- user_from_token: auth::UserFromToken,
+ user_from_token: auth::UserIdFromAuth,
) -> UserResponse<()> {
tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?;
tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?;
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 068c2f30c79..8fc0dad452a 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -130,7 +130,7 @@ pub async fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpR
&http_req,
(),
|state, user, _, _| user_core::signout(state, user),
- &auth::DashboardNoPermissionAuth,
+ &auth::AnyPurposeOrLoginTokenAuth,
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 2f5f55b8434..c05e4514aaa 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -871,6 +871,47 @@ where
}
}
+#[cfg(feature = "olap")]
+#[derive(Debug)]
+pub struct AnyPurposeOrLoginTokenAuth;
+
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for AnyPurposeOrLoginTokenAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> {
+ let payload =
+ parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ let purpose_exists = payload.purpose.is_some();
+ let role_id_exists = payload.role_id.is_some();
+
+ if purpose_exists ^ role_id_exists {
+ Ok((
+ UserIdFromAuth {
+ user_id: payload.user_id.clone(),
+ },
+ AuthenticationType::SinglePurposeOrLoginJwt {
+ user_id: payload.user_id,
+ purpose: payload.purpose,
+ role_id: payload.role_id,
+ },
+ ))
+ } else {
+ Err(errors::ApiErrorResponse::InvalidJwtToken.into())
+ }
+ }
+}
+
#[derive(Debug, Default)]
pub struct AdminApiAuth;
@@ -2504,17 +2545,27 @@ where
T: serde::de::DeserializeOwned,
A: SessionStateInfo + Sync,
{
- let token = match get_cookie_from_header(headers).and_then(cookies::parse_cookie) {
- Ok(cookies) => cookies,
- Err(error) => {
- let token = get_jwt_from_authorization_header(headers);
- if token.is_err() {
- logger::error!(?error);
- }
- token?.to_owned()
- }
+ let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::parse_cookie);
+ let auth_header_token_result = get_jwt_from_authorization_header(headers);
+ let force_cookie = state.conf().user.force_cookies;
+
+ logger::info!(
+ user_agent = ?headers.get(headers::USER_AGENT),
+ header_names = ?headers.keys().collect::<Vec<_>>(),
+ is_token_equal =
+ auth_header_token_result.as_deref().ok() == cookie_token_result.as_deref().ok(),
+ cookie_error = ?cookie_token_result.as_ref().err(),
+ token_error = ?auth_header_token_result.as_ref().err(),
+ force_cookie,
+ );
+
+ let final_token = if force_cookie {
+ cookie_token_result?
+ } else {
+ auth_header_token_result?.to_owned()
};
- decode_jwt(&token, state).await
+
+ decode_jwt(&final_token, state).await
}
#[cfg(feature = "v1")]
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index dab85eb3cdd..a3ac1159ddb 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -36,6 +36,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch"
force_two_factor_auth = false
+force_cookies = true
[locker]
host = ""
|
2024-11-18T11:34:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR will add logging for cookies and also make signout API accessible by any SPT.
### 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/integration_test.toml`
`config/deployments/production.toml`
`config/deployments/sandbox.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 #6598.
## How did you test 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 following behaviour applies only to integ and not for sandbox and prod.
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNzJkNDU0YTAtM2I3YS00MzZiLTllNjMtMmU5ZDQ5YzI3NmZjIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTI4MDg1Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjEwMDg5MSwib3JnX2lkIjoib3JnX05qeWR3eXhpRW5OQjk2QldobjlwIiwicHJvZmlsZV9pZCI6InByb183bGVMTnpFakVtRWVha1ZKTlJSbSJ9.g7InEVOcYqKSh2zNPBrq20l6O5MppE3-wKqj2YYBkBM'
```
If cookie is not present even if the auth header is present, BE will throw the following error
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Cookie",
"code": "IR_26"
}
}
```
- If cookie will be given priority if both are present.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ea81432e3eb72d9a2e139e26741a42cdd8d31202
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6645
|
Bug: [FEAT] Multiple credential support for a connector in Cypress
## Requirement
Execute cypress tests for a connector having **multiple credentials** which can be used for different scenarios (one api key for `cards`, another for `bank redirects` and etc.,).
## Implementation
### Introduce new format for `creds.json`
`creds.json` should include both the formats. if a connector requires us passing **multiple credentials**, then that connector api key object **should** include multiple `connector_account_details` object all named under a generic name `connector_<number>` where `number` is an `integer`.
Refer example given below for more clarity:
```json
// connector having multiple credentials
<connector_name_1>: {
"connector_1": {
"connector_account_details": {
"auth_type": "KeyType",
"api_key": "",
"api_secret": "",
"key1": "",
"key2": ""
},
"metadata": {}
},
"connector_2": {
"connector_account_details": {
"auth_type": "KeyType",
"api_key": "",
"api_secret": "",
"key1": "",
"key2": ""
},
"metadata": {}
},
},
// connector with a single credential
<connector_name_2>: {
"connector_account_details": {
"auth_type": "KeyType",
"api_key": "",
"api_secret": "",
"key1": "",
"key2": ""
}
}
```
### Introduce new `object` (`Configs`) for `connector.js`
Within `connector.js`, introduce new object called as `Configs` alongside to `Request` and `Response` where user can define `flags` to achieve granular control over what test is being run.
An example implementation given below for reference:
```js
getCustomExchange({
Configs: {
TRIGGER_SKIP: true, // skips redirection flow from running. takes in a boolean
DELAY: {
STATUS: true, // flag to turn delay feature on or off. takes in a boolean
TIMEOUT: 5000, // timeout in milliseconds
},
CONNECTOR_CREDENTIAL: connector_1 / connector_2 // flag to route tests to a specific profile
// etc.,
},
Requst: {},
Response: {}
}),
```
### Modify `getValueByKey` function in `Utils.js`
Validate if `connector_account_details` dot exist within `<connector>` object in creds.
If it does not, start a loop and see if `connector_account_details` exist within every object. If true, return the `connector_account_details` while setting an object as a Cypress environment flag (`MULTIPLE_CONNECTORS`) with status `true` and length. If any validation fails, directly return the object (`data[key]`).
An example implementation given below for reference:
```js
if (data && typeof data === "object" && key in data) {
// Connector object has multiple keys
if (typeof data[key].connector_account_details === "undefined") {
const keys = Object.keys(data[key]);
for (let i = 0; i < keys.length; i++) {
const currentItem = data[key][keys[i]];
if (currentItem.hasOwnProperty("connector_account_details")) {
Cypress.env("MULTIPLE_CONNECTORS", {
status: true,
count: keys.length,
});
return currentItem;
}
}
}
return data[key];
} else {
return null;
}
```
### Add a new test to MCA create call
If `MULTIPLE_CONNECTORS.status` is `TRUE`. Check `MULTIPLE_CONNECTORS.count` and create `profile` and `mca` beneath that `profile` based on the number of `count`.
An example of possible implementation given below for reference:
```js
if (Cypress.env("MULTIPLE_CONNECTORS")?.status) {
for (let i = 0; i < Cypress.env("MULTIPLE_CONNECTORS").count; i++) {
cy.createBusinessProfileTest(
createBusinessProfileBody,
globalState,
"profile" + i // new optional fields
);
cy.createConnectorCallTest(
"payment_processor",
createConnectorBody,
payment_methods_enabled,
globalState,
"profile" + i, // new optional fields
"merchantConnector" + i // new optional fields
);
}
}
```
Store these created `profile_id`s and `mca`s in `globalState` for future usage.
Pass `CONNECTOR_CREDENTIAL` value as `connector_1` or `connector_2` in `<connector>.js`
In `commands.js`, `execute` these configs before a `request` has been made.
`execute` here means to make these configs work.
Preferably, make this execution of configs a function and pass the values accordingly along with trace to find from where the function has been called.
## Limitations
- Cypress cannot call itself unless a wrapper around Cypress is written (`Rustpress`?)
- This stops us from running the entire test suite against every credentials
- One possible work around for this is to have multiple keys (`cybersource_1`, `cybersource_2`) but this will result in a lot of confusion
- Current implementation **requires** the user to mandatorily pass a `CONNECTOR_CREDENTIAL` config to pass a different `profileId`
- Hence, the tests will only run once but, specific tests like `incremental auth` will be forced to run against different credential
- `00025-IncrementalAuth.cy.js` can be stopped from execution based on `MULTIPLE_CONNECTORS` environment variable as it is set during run time and the file is read asynchronously when the execution starts (to address this, we will have to make a function call to see if it is set during run time and it is, then skip)
|
2024-11-17T07:12:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR introduces 2 new features:
- Multiple credentials for a connector
- Configuration flags
closes #6645 (check this issue for detailed documentation / flow / explanation)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- We need to run tests against multiple connector api keys for a single connector
- We also need configuration flag support to selectively grant a test certain features / options
## How did you test 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 Cybersource with `multiple creds` (takes only from first `connector_1`):
<img width="594" alt="image" src="https://github.com/user-attachments/assets/7c05742c-6331-417a-8699-731285463560">
Cybersource with `multiple creds` (along with `incremental auth`):
<img width="554" alt="image" src="https://github.com/user-attachments/assets/664defa0-2fa4-4189-82f1-987421a48374">
(incremental auth fails from the connector's end and hence 4 failures)
Stripe:
<img width="676" alt="image" src="https://github.com/user-attachments/assets/cc1f2c16-bc9d-417e-94da-18870d9399cd">
Wise:
<img width="567" alt="image" src="https://github.com/user-attachments/assets/512e8bbc-c979-4791-8263-3253e61e193c">
PML:
<img width="549" alt="image" src="https://github.com/user-attachments/assets/e53a72e0-fddc-4351-8557-07058e223be8">
have disabled incremental auth from executing:
<img width="680" alt="image" src="https://github.com/user-attachments/assets/e2cd2e96-326e-422a-a9c4-21bd5a2b86c2">
trustpay refunds (multiple creds):
<img width="675" alt="image" src="https://github.com/user-attachments/assets/7fcb908f-de34-4d28-ac10-e4082ad3d54c">
i commented iDEAL redirections to check, error is being thrown from connector's end and there's nothing much i can do:
<img width="607" alt="image" src="https://github.com/user-attachments/assets/689979c8-d044-4b5f-a5a8-9ea8e15860e1">
<img width="1364" alt="image" src="https://github.com/user-attachments/assets/b0261af6-68c7-445f-af79-5e9d16bdc7fa">
<img width="555" alt="image" src="https://github.com/user-attachments/assets/fae0d997-695b-4db2-8f3e-0afad44c9c3e">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `prettier . --write`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
797a0db7733c5b387564fb1bbc106d054c8dffa6
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6594
|
Bug: fix(analytics): fix `authentication_type` and `card_last_4` fields serialization for payment_intent_filters
There is a serialization issue for `card_last_4` and `authentication_type` fields when filters are getting applied for `PaymentIntentFilters`.
- `card_last_4` was being processed as `card_last4` .
- `auth_type` is being used to add the filters and not serialized into `Authentication_type`.
Need to serialize the fields properly, before applying these filters in the query.
|
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index dd51c97d935..365abd71edc 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -63,11 +63,15 @@ pub enum PaymentIntentDimensions {
Currency,
ProfileId,
Connector,
+ #[strum(serialize = "authentication_type")]
+ #[serde(rename = "authentication_type")]
AuthType,
PaymentMethod,
PaymentMethodType,
CardNetwork,
MerchantId,
+ #[strum(serialize = "card_last_4")]
+ #[serde(rename = "card_last_4")]
CardLast4,
CardIssuer,
ErrorReason,
|
2024-11-18T10:46:29Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
There is a serialization issue for `card_last_4` and `authentication_type` fields when filters are getting applied for `PaymentIntentFilters`.
`card_last_4` was being processed as `card_last4` .
`auth_type` is being used to add the filters and not serialized into `Authentication_type`.
Made the changes to properly serialize `card_last_4` and `authentication_type` filters for `PaymentIntentFilters` now.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 filters issue for some fields for Payment Intents.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
`authentication_type`:
Hit the curl for any metric of payment_intents (sessionized metrics):
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \
--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-10-14T18:30:00Z",
"endTime": "2024-10-22T15:24:00Z"
},
"groupByNames": [
"currency"
],
"filters": {
"auth_type": [
"no_three_ds"
]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
]
}
]'
```
You can see the `authentication_type` filter that is getting applied in the query.

`card_last_4`:
Hit the curl for any metric of payment_intents (sessionized metrics):
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjA4NzM4Miwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.3bV2aTF7uFAtELFBuKe-_hIZHY35Zv5ij51F-slCYIg' \
--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-10-14T18:30:00Z",
"endTime": "2024-10-22T15:24:00Z"
},
"groupByNames": [
"currency"
],
"filters": {
"card_last_4": [
"4242"
]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_payment_processed_amount"
]
}
]'
```
You can see the `card_last_4` filter that is getting applied in the query.

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d32397f060731f51a15634e221117a554b8b3721
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6615
|
Bug: feat(analytics): Add refund sessionized metrics for Analytics V2 dashboard
Create the new refund sessionized metrics for Analytics V2 dashboard.
|
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index f56e875f720..cd870c12b23 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -16,7 +16,9 @@ use super::{
distribution::PaymentDistributionRow, filters::PaymentFilterRow, metrics::PaymentMetricRow,
},
query::{Aggregate, ToSql, Window},
- refunds::{filters::RefundFilterRow, metrics::RefundMetricRow},
+ refunds::{
+ distribution::RefundDistributionRow, filters::RefundFilterRow, metrics::RefundMetricRow,
+ },
sdk_events::{filters::SdkEventFilter, metrics::SdkEventMetricRow},
types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, QueryExecutionError},
};
@@ -170,6 +172,7 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for Clickhous
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {}
impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {}
impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {}
+impl super::refunds::distribution::RefundDistributionAnalytics for ClickhouseClient {}
impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {}
impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {}
@@ -300,6 +303,16 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
}
}
+impl TryInto<RefundDistributionRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<RefundDistributionRow, Self::Error> {
+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
+ "Failed to parse RefundDistributionRow in clickhouse results",
+ ))
+ }
+}
+
impl TryInto<FrmMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 224cd82ccd3..13fdefe864d 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -29,6 +29,7 @@ use hyperswitch_interfaces::secrets_interface::{
secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
SecretManagementInterface, SecretsManagementError,
};
+use refunds::distribution::{RefundDistribution, RefundDistributionRow};
pub use types::AnalyticsDomain;
pub mod lambda_utils;
pub mod utils;
@@ -52,7 +53,7 @@ use api_models::analytics::{
sdk_events::{
SdkEventDimensions, SdkEventFilters, SdkEventMetrics, SdkEventMetricsBucketIdentifier,
},
- Distribution, Granularity, TimeRange,
+ Granularity, PaymentDistributionBody, RefundDistributionBody, TimeRange,
};
use clickhouse::ClickhouseClient;
pub use clickhouse::ClickhouseConfig;
@@ -215,7 +216,7 @@ impl AnalyticsProvider {
pub async fn get_payment_distribution(
&self,
- distribution: &Distribution,
+ distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
@@ -528,6 +529,116 @@ impl AnalyticsProvider {
.await
}
+ pub async fn get_refund_distribution(
+ &self,
+ distribution: &RefundDistributionBody,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ ) -> types::MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> {
+ // Metrics to get the fetch time for each payment metric
+ metrics::request::record_operation_time(
+ async {
+ match self {
+ Self::Sqlx(pool) => {
+ distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::Clickhouse(pool) => {
+ distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::CombinedCkh(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ ));
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution")
+ },
+ _ => {}
+
+ };
+
+ ckh_result
+ }
+ Self::CombinedSqlx(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ distribution.distribution_for
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ ));
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres payments analytics distribution")
+ },
+ _ => {}
+
+ };
+
+ sqlx_result
+ }
+ }
+ },
+ &metrics::METRIC_FETCH_TIME,
+ &distribution.distribution_for,
+ self,
+ )
+ .await
+ }
+
pub async fn get_frm_metrics(
&self,
metric: &FrmMetrics,
diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs
index 213b6244574..055572a0805 100644
--- a/crates/analytics/src/payments/distribution.rs
+++ b/crates/analytics/src/payments/distribution.rs
@@ -2,7 +2,7 @@ use api_models::analytics::{
payments::{
PaymentDimensions, PaymentDistributions, PaymentFilters, PaymentMetricsBucketIdentifier,
},
- Distribution, Granularity, TimeRange,
+ Granularity, PaymentDistributionBody, TimeRange,
};
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
@@ -53,7 +53,7 @@ where
#[allow(clippy::too_many_arguments)]
async fn load_distribution(
&self,
- distribution: &Distribution,
+ distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
@@ -75,7 +75,7 @@ where
{
async fn load_distribution(
&self,
- distribution: &Distribution,
+ distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs
index 241754ee041..de5cb3ae5e8 100644
--- a/crates/analytics/src/payments/distribution/payment_error_message.rs
+++ b/crates/analytics/src/payments/distribution/payment_error_message.rs
@@ -1,6 +1,6 @@
use api_models::analytics::{
payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier},
- Distribution, Granularity, TimeRange,
+ Granularity, PaymentDistributionBody, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums as storage_enums;
@@ -31,7 +31,7 @@ where
{
async fn load_distribution(
&self,
- distribution: &Distribution,
+ distribution: &PaymentDistributionBody,
dimensions: &[PaymentDimensions],
auth: &AuthInfo,
filters: &PaymentFilters,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index caa112ec175..cbb0cf6737c 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -9,7 +9,7 @@ use api_models::{
frm::{FrmDimensions, FrmTransactionType},
payment_intents::PaymentIntentDimensions,
payments::{PaymentDimensions, PaymentDistributions},
- refunds::{RefundDimensions, RefundType},
+ refunds::{RefundDimensions, RefundDistributions, RefundType},
sdk_events::{SdkEventDimensions, SdkEventNames},
Granularity,
},
@@ -488,6 +488,7 @@ impl_to_sql_for_to_string!(
PaymentIntentDimensions,
&PaymentDistributions,
RefundDimensions,
+ &RefundDistributions,
FrmDimensions,
PaymentMethod,
PaymentMethodType,
diff --git a/crates/analytics/src/refunds.rs b/crates/analytics/src/refunds.rs
index 590dc148ebf..ed6f396ccec 100644
--- a/crates/analytics/src/refunds.rs
+++ b/crates/analytics/src/refunds.rs
@@ -1,6 +1,7 @@
pub mod accumulator;
mod core;
+pub mod distribution;
pub mod filters;
pub mod metrics;
pub mod types;
diff --git a/crates/analytics/src/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs
index add38c98162..840d46bbab7 100644
--- a/crates/analytics/src/refunds/accumulator.rs
+++ b/crates/analytics/src/refunds/accumulator.rs
@@ -1,19 +1,56 @@
-use api_models::analytics::refunds::RefundMetricsBucketValue;
+use api_models::analytics::refunds::{
+ ErrorMessagesResult, ReasonsResult, RefundMetricsBucketValue,
+};
+use bigdecimal::ToPrimitive;
use diesel_models::enums as storage_enums;
-use super::metrics::RefundMetricRow;
+use super::{distribution::RefundDistributionRow, metrics::RefundMetricRow};
#[derive(Debug, Default)]
pub struct RefundMetricsAccumulator {
pub refund_success_rate: SuccessRateAccumulator,
pub refund_count: CountAccumulator,
pub refund_success: CountAccumulator,
- pub processed_amount: PaymentProcessedAmountAccumulator,
+ pub processed_amount: RefundProcessedAmountAccumulator,
+ pub refund_reason: RefundReasonAccumulator,
+ pub refund_reason_distribution: RefundReasonDistributionAccumulator,
+ pub refund_error_message: RefundReasonAccumulator,
+ pub refund_error_message_distribution: RefundErrorMessageDistributionAccumulator,
}
#[derive(Debug, Default)]
-pub struct SuccessRateAccumulator {
- pub success: i64,
+pub struct RefundReasonDistributionRow {
+ pub count: i64,
+ pub total: i64,
+ pub refund_reason: String,
+}
+
+#[derive(Debug, Default)]
+pub struct RefundReasonDistributionAccumulator {
+ pub refund_reason_vec: Vec<RefundReasonDistributionRow>,
+}
+
+#[derive(Debug, Default)]
+pub struct RefundErrorMessageDistributionRow {
+ pub count: i64,
pub total: i64,
+ pub refund_error_message: String,
+}
+
+#[derive(Debug, Default)]
+pub struct RefundErrorMessageDistributionAccumulator {
+ pub refund_error_message_vec: Vec<RefundErrorMessageDistributionRow>,
+}
+
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct RefundReasonAccumulator {
+ pub count: u64,
+}
+
+#[derive(Debug, Default)]
+pub struct SuccessRateAccumulator {
+ pub success: u32,
+ pub total: u32,
}
#[derive(Debug, Default)]
#[repr(transparent)]
@@ -21,8 +58,8 @@ pub struct CountAccumulator {
pub count: Option<i64>,
}
#[derive(Debug, Default)]
-#[repr(transparent)]
-pub struct PaymentProcessedAmountAccumulator {
+pub struct RefundProcessedAmountAccumulator {
+ pub count: Option<i64>,
pub total: Option<i64>,
}
@@ -34,6 +71,93 @@ pub trait RefundMetricAccumulator {
fn collect(self) -> Self::MetricOutput;
}
+pub trait RefundDistributionAccumulator {
+ type DistributionOutput;
+
+ fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow);
+
+ fn collect(self) -> Self::DistributionOutput;
+}
+
+impl RefundDistributionAccumulator for RefundReasonDistributionAccumulator {
+ type DistributionOutput = Option<Vec<ReasonsResult>>;
+
+ fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) {
+ self.refund_reason_vec.push(RefundReasonDistributionRow {
+ count: distribution.count.unwrap_or_default(),
+ total: distribution
+ .total
+ .clone()
+ .map(|i| i.to_i64().unwrap_or_default())
+ .unwrap_or_default(),
+ refund_reason: distribution.refund_reason.clone().unwrap_or_default(),
+ })
+ }
+
+ fn collect(mut self) -> Self::DistributionOutput {
+ if self.refund_reason_vec.is_empty() {
+ None
+ } else {
+ self.refund_reason_vec.sort_by(|a, b| b.count.cmp(&a.count));
+ let mut res: Vec<ReasonsResult> = Vec::new();
+ for val in self.refund_reason_vec.into_iter() {
+ let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0
+ / f64::from(u32::try_from(val.total).ok()?);
+
+ res.push(ReasonsResult {
+ reason: val.refund_reason,
+ count: val.count,
+ percentage: (perc * 100.0).round() / 100.0,
+ })
+ }
+
+ Some(res)
+ }
+ }
+}
+
+impl RefundDistributionAccumulator for RefundErrorMessageDistributionAccumulator {
+ type DistributionOutput = Option<Vec<ErrorMessagesResult>>;
+
+ fn add_distribution_bucket(&mut self, distribution: &RefundDistributionRow) {
+ self.refund_error_message_vec
+ .push(RefundErrorMessageDistributionRow {
+ count: distribution.count.unwrap_or_default(),
+ total: distribution
+ .total
+ .clone()
+ .map(|i| i.to_i64().unwrap_or_default())
+ .unwrap_or_default(),
+ refund_error_message: distribution
+ .refund_error_message
+ .clone()
+ .unwrap_or_default(),
+ })
+ }
+
+ fn collect(mut self) -> Self::DistributionOutput {
+ if self.refund_error_message_vec.is_empty() {
+ None
+ } else {
+ self.refund_error_message_vec
+ .sort_by(|a, b| b.count.cmp(&a.count));
+ let mut res: Vec<ErrorMessagesResult> = Vec::new();
+ for val in self.refund_error_message_vec.into_iter() {
+ let perc = f64::from(u32::try_from(val.count).ok()?) * 100.0
+ / f64::from(u32::try_from(val.total).ok()?);
+
+ res.push(ErrorMessagesResult {
+ error_message: val.refund_error_message,
+ count: val.count,
+ percentage: (perc * 100.0).round() / 100.0,
+ })
+ }
+
+ Some(res)
+ }
+ }
+}
+
impl RefundMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
@@ -50,62 +174,103 @@ impl RefundMetricAccumulator for CountAccumulator {
}
}
-impl RefundMetricAccumulator for PaymentProcessedAmountAccumulator {
- type MetricOutput = (Option<u64>, Option<u64>);
+impl RefundMetricAccumulator for RefundProcessedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
self.total = match (
self.total,
- metrics
- .total
- .as_ref()
- .and_then(bigdecimal::ToPrimitive::to_i64),
+ 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 = match (self.count, 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 {
- (self.total.and_then(|i| u64::try_from(i).ok()), Some(0))
+ let total = u64::try_from(self.total.unwrap_or_default()).ok();
+ let count = self.count.and_then(|i| u64::try_from(i).ok());
+
+ (total, count, Some(0))
}
}
impl RefundMetricAccumulator for SuccessRateAccumulator {
- type MetricOutput = Option<f64>;
+ type MetricOutput = (Option<u32>, Option<u32>, Option<f64>);
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
if let Some(ref refund_status) = metrics.refund_status {
if refund_status.as_ref() == &storage_enums::RefundStatus::Success {
- self.success += metrics.count.unwrap_or_default();
+ if let Some(success) = metrics
+ .count
+ .and_then(|success| u32::try_from(success).ok())
+ {
+ self.success += success;
+ }
}
};
- self.total += metrics.count.unwrap_or_default();
+ 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
+ if self.total == 0 {
+ (None, None, None)
} else {
- Some(
- f64::from(u32::try_from(self.success).ok()?) * 100.0
- / f64::from(u32::try_from(self.total).ok()?),
- )
+ let success = Some(self.success);
+ 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,
+ };
+ (success, total, success_rate)
+ }
+ }
+}
+
+impl RefundMetricAccumulator for RefundReasonAccumulator {
+ type MetricOutput = Option<u64>;
+
+ fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
+ if let Some(count) = metrics.count {
+ if let Ok(count_u64) = u64::try_from(count) {
+ self.count += count_u64;
+ }
}
}
+
+ fn collect(self) -> Self::MetricOutput {
+ Some(self.count)
+ }
}
impl RefundMetricsAccumulator {
pub fn collect(self) -> RefundMetricsBucketValue {
- let (refund_processed_amount, refund_processed_amount_in_usd) =
+ let (successful_refunds, total_refunds, refund_success_rate) =
+ self.refund_success_rate.collect();
+ let (refund_processed_amount, refund_processed_count, refund_processed_amount_in_usd) =
self.processed_amount.collect();
RefundMetricsBucketValue {
- refund_success_rate: self.refund_success_rate.collect(),
+ successful_refunds,
+ total_refunds,
+ refund_success_rate,
refund_count: self.refund_count.collect(),
refund_success_count: self.refund_success.collect(),
refund_processed_amount,
refund_processed_amount_in_usd,
+ refund_processed_count,
+ refund_reason_distribution: self.refund_reason_distribution.collect(),
+ refund_error_message_distribution: self.refund_error_message_distribution.collect(),
+ refund_reason_count: self.refund_reason.collect(),
+ refund_error_message_count: self.refund_error_message.collect(),
}
}
}
diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs
index e3bfa4da9d1..205600b9259 100644
--- a/crates/analytics/src/refunds/core.rs
+++ b/crates/analytics/src/refunds/core.rs
@@ -1,15 +1,17 @@
#![allow(dead_code)]
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use api_models::analytics::{
refunds::{
- RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse,
+ RefundDimensions, RefundDistributions, RefundMetrics, RefundMetricsBucketIdentifier,
+ RefundMetricsBucketResponse,
},
GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse,
RefundsAnalyticsMetadata, RefundsMetricsResponse,
};
use bigdecimal::ToPrimitive;
use common_enums::Currency;
+use common_utils::errors::CustomResult;
use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
@@ -19,17 +21,31 @@ use router_env::{
};
use super::{
+ distribution::RefundDistributionRow,
filters::{get_refund_filter_for_dimension, RefundFilterRow},
+ metrics::RefundMetricRow,
RefundMetricsAccumulator,
};
use crate::{
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics,
- refunds::RefundMetricAccumulator,
+ refunds::{accumulator::RefundDistributionAccumulator, RefundMetricAccumulator},
AnalyticsProvider,
};
+#[derive(Debug)]
+pub enum TaskType {
+ MetricTask(
+ RefundMetrics,
+ CustomResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>, AnalyticsError>,
+ ),
+ DistributionTask(
+ RefundDistributions,
+ CustomResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, AnalyticsError>,
+ ),
+}
+
pub async fn get_metrics(
pool: &AnalyticsProvider,
ex_rates: &ExchangeRates,
@@ -62,65 +78,145 @@ pub async fn get_metrics(
)
.await
.change_context(AnalyticsError::UnknownError);
- (metric_type, data)
+ TaskType::MetricTask(metric_type, data)
+ }
+ .instrument(task_span),
+ );
+ }
+
+ if let Some(distribution) = req.clone().distribution {
+ let req = req.clone();
+ let pool = pool.clone();
+ let task_span = tracing::debug_span!(
+ "analytics_refunds_distribution_query",
+ refund_distribution = distribution.distribution_for.as_ref()
+ );
+
+ let auth_scoped = auth.to_owned();
+ set.spawn(
+ async move {
+ let data = pool
+ .get_refund_distribution(
+ &distribution,
+ &req.group_by_names.clone(),
+ &auth_scoped,
+ &req.filters,
+ &req.time_series.map(|t| t.granularity),
+ &req.time_range,
+ )
+ .await
+ .change_context(AnalyticsError::UnknownError);
+ TaskType::DistributionTask(distribution.distribution_for, data)
}
.instrument(task_span),
);
}
- while let Some((metric, data)) = set
+ while let Some(task_type) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
- let data = data?;
- let attributes = &add_attributes([
- ("metric_type", metric.to_string()),
- ("source", pool.to_string()),
- ]);
-
- let value = u64::try_from(data.len());
- if let Ok(val) = value {
- metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes);
- logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
- }
+ match task_type {
+ TaskType::MetricTask(metric, data) => {
+ let data = data?;
+ let attributes = &add_attributes([
+ ("metric_type", metric.to_string()),
+ ("source", pool.to_string()),
+ ]);
- for (id, value) in data {
- logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
- let metrics_builder = metrics_accumulator.entry(id).or_default();
- match metric {
- RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => {
- metrics_builder
- .refund_success_rate
- .add_metrics_bucket(&value)
+ let value = u64::try_from(data.len());
+ if let Ok(val) = value {
+ metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes);
+ logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
- RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => {
- metrics_builder.refund_count.add_metrics_bucket(&value)
+
+ for (id, value) in data {
+ logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
+ let metrics_builder = metrics_accumulator.entry(id).or_default();
+ match metric {
+ RefundMetrics::RefundSuccessRate
+ | RefundMetrics::SessionizedRefundSuccessRate => metrics_builder
+ .refund_success_rate
+ .add_metrics_bucket(&value),
+ RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => {
+ metrics_builder.refund_count.add_metrics_bucket(&value)
+ }
+ RefundMetrics::RefundSuccessCount
+ | RefundMetrics::SessionizedRefundSuccessCount => {
+ metrics_builder.refund_success.add_metrics_bucket(&value)
+ }
+ RefundMetrics::RefundProcessedAmount
+ | RefundMetrics::SessionizedRefundProcessedAmount => {
+ metrics_builder.processed_amount.add_metrics_bucket(&value)
+ }
+ RefundMetrics::SessionizedRefundReason => {
+ metrics_builder.refund_reason.add_metrics_bucket(&value)
+ }
+ RefundMetrics::SessionizedRefundErrorMessage => metrics_builder
+ .refund_error_message
+ .add_metrics_bucket(&value),
+ }
}
- RefundMetrics::RefundSuccessCount
- | RefundMetrics::SessionizedRefundSuccessCount => {
- metrics_builder.refund_success.add_metrics_bucket(&value)
+
+ logger::debug!(
+ "Analytics Accumulated Results: metric: {}, results: {:#?}",
+ metric,
+ metrics_accumulator
+ );
+ }
+ TaskType::DistributionTask(distribution, data) => {
+ let data = data?;
+ let attributes = &add_attributes([
+ ("distribution_type", distribution.to_string()),
+ ("source", pool.to_string()),
+ ]);
+ let value = u64::try_from(data.len());
+ if let Ok(val) = value {
+ metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes);
+ logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
- RefundMetrics::RefundProcessedAmount
- | RefundMetrics::SessionizedRefundProcessedAmount => {
- metrics_builder.processed_amount.add_metrics_bucket(&value)
+
+ for (id, value) in data {
+ logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}");
+
+ let metrics_builder = metrics_accumulator.entry(id).or_default();
+ match distribution {
+ RefundDistributions::SessionizedRefundReason => metrics_builder
+ .refund_reason_distribution
+ .add_distribution_bucket(&value),
+ RefundDistributions::SessionizedRefundErrorMessage => metrics_builder
+ .refund_error_message_distribution
+ .add_distribution_bucket(&value),
+ }
}
+ logger::debug!(
+ "Analytics Accumulated Results: distribution: {}, results: {:#?}",
+ distribution,
+ metrics_accumulator
+ );
}
}
-
- logger::debug!(
- "Analytics Accumulated Results: metric: {}, results: {:#?}",
- metric,
- metrics_accumulator
- );
}
+
+ let mut success = 0;
+ let mut total = 0;
let mut total_refund_processed_amount = 0;
let mut total_refund_processed_amount_in_usd = 0;
+ let mut total_refund_processed_count = 0;
+ let mut total_refund_reason_count = 0;
+ let mut total_refund_error_message_count = 0;
let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let mut collected_values = val.collect();
+ if let Some(success_count) = collected_values.successful_refunds {
+ success += success_count;
+ }
+ if let Some(total_count) = collected_values.total_refunds {
+ total += total_count;
+ }
if let Some(amount) = collected_values.refund_processed_amount {
let amount_in_usd = id
.currency
@@ -142,18 +238,34 @@ pub async fn get_metrics(
total_refund_processed_amount += amount;
total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
+ if let Some(count) = collected_values.refund_processed_count {
+ total_refund_processed_count += count;
+ }
+ if let Some(total_count) = collected_values.refund_reason_count {
+ total_refund_reason_count += total_count;
+ }
+ if let Some(total_count) = collected_values.refund_error_message_count {
+ total_refund_error_message_count += total_count;
+ }
RefundMetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
-
+ let total_refund_success_rate = match (success, total) {
+ (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
Ok(RefundsMetricsResponse {
query_data,
meta_data: [RefundsAnalyticsMetadata {
+ total_refund_success_rate,
total_refund_processed_amount: Some(total_refund_processed_amount),
total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd),
+ total_refund_processed_count: Some(total_refund_processed_count),
+ total_refund_reason_count: Some(total_refund_reason_count),
+ total_refund_error_message_count: Some(total_refund_error_message_count),
}],
})
}
@@ -229,6 +341,8 @@ pub async fn get_filters(
RefundDimensions::Connector => fil.connector,
RefundDimensions::RefundType => fil.refund_type.map(|i| i.as_ref().to_string()),
RefundDimensions::ProfileId => fil.profile_id,
+ RefundDimensions::RefundReason => fil.refund_reason,
+ RefundDimensions::RefundErrorMessage => fil.refund_error_message,
})
.collect::<Vec<String>>();
res.query_data.push(RefundFilterValue {
diff --git a/crates/analytics/src/refunds/distribution.rs b/crates/analytics/src/refunds/distribution.rs
new file mode 100644
index 00000000000..962f74acd1a
--- /dev/null
+++ b/crates/analytics/src/refunds/distribution.rs
@@ -0,0 +1,105 @@
+use api_models::analytics::{
+ refunds::{
+ RefundDimensions, RefundDistributions, RefundFilters, RefundMetricsBucketIdentifier,
+ RefundType,
+ },
+ Granularity, RefundDistributionBody, TimeRange,
+};
+use diesel_models::enums as storage_enums;
+use time::PrimitiveDateTime;
+
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
+};
+
+mod sessionized_distribution;
+
+#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
+pub struct RefundDistributionRow {
+ pub currency: Option<DBEnumWrapper<storage_enums::Currency>>,
+ pub refund_status: Option<DBEnumWrapper<storage_enums::RefundStatus>>,
+ pub connector: Option<String>,
+ pub refund_type: Option<DBEnumWrapper<RefundType>>,
+ pub profile_id: Option<String>,
+ pub total: Option<bigdecimal::BigDecimal>,
+ pub count: Option<i64>,
+ pub refund_reason: Option<String>,
+ pub refund_error_message: Option<String>,
+ #[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>,
+}
+
+pub trait RefundDistributionAnalytics: LoadRow<RefundDistributionRow> {}
+
+#[async_trait::async_trait]
+pub trait RefundDistribution<T>
+where
+ T: AnalyticsDataSource + RefundDistributionAnalytics,
+{
+ #[allow(clippy::too_many_arguments)]
+ async fn load_distribution(
+ &self,
+ distribution: &RefundDistributionBody,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>>;
+}
+
+#[async_trait::async_trait]
+impl<T> RefundDistribution<T> for RefundDistributions
+where
+ T: AnalyticsDataSource + RefundDistributionAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_distribution(
+ &self,
+ distribution: &RefundDistributionBody,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> {
+ match self {
+ Self::SessionizedRefundReason => {
+ sessionized_distribution::RefundReason
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::SessionizedRefundErrorMessage => {
+ sessionized_distribution::RefundErrorMessage
+ .load_distribution(
+ distribution,
+ dimensions,
+ auth,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ }
+ }
+}
diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution.rs
new file mode 100644
index 00000000000..391b855e96e
--- /dev/null
+++ b/crates/analytics/src/refunds/distribution/sessionized_distribution.rs
@@ -0,0 +1,7 @@
+mod refund_error_message;
+mod refund_reason;
+
+pub(super) use refund_error_message::RefundErrorMessage;
+pub(super) use refund_reason::RefundReason;
+
+pub use super::{RefundDistribution, RefundDistributionAnalytics, RefundDistributionRow};
diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs
new file mode 100644
index 00000000000..a4268c86cbe
--- /dev/null
+++ b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_error_message.rs
@@ -0,0 +1,177 @@
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, RefundDistributionBody, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::{RefundDistribution, RefundDistributionRow};
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundErrorMessage;
+
+#[async_trait::async_trait]
+impl<T> RefundDistribution<T> for RefundErrorMessage
+where
+ T: AnalyticsDataSource + super::RefundDistributionAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_distribution(
+ &self,
+ distribution: &RefundDistributionBody,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(&distribution.distribution_for)
+ .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()?;
+
+ query_builder
+ .add_filter_clause(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Failure,
+ )
+ .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(&distribution.distribution_for)
+ .attach_printable("Error grouping by distribution_for")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ for dim in dimensions.iter() {
+ query_builder.add_outer_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_outer_select_column(&distribution.distribution_for)
+ .switch()?;
+ query_builder.add_outer_select_column("count").switch()?;
+ query_builder
+ .add_outer_select_column("start_bucket")
+ .switch()?;
+ query_builder
+ .add_outer_select_column("end_bucket")
+ .switch()?;
+ let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?;
+
+ query_builder
+ .add_outer_select_column(Window::Sum {
+ field: "count",
+ partition_by: Some(sql_dimensions),
+ order_by: None,
+ alias: Some("total"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_top_n_clause(
+ dimensions,
+ distribution.distribution_cardinality.into(),
+ "count",
+ Order::Descending,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<RefundDistributionRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.refund_status.as_ref().map(|i| i.0.to_string()),
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.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<
+ Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs
new file mode 100644
index 00000000000..a2a933db8cb
--- /dev/null
+++ b/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs
@@ -0,0 +1,169 @@
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, RefundDistributionBody, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::{RefundDistribution, RefundDistributionRow};
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundReason;
+
+#[async_trait::async_trait]
+impl<T> RefundDistribution<T> for RefundReason
+where
+ T: AnalyticsDataSource + super::RefundDistributionAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_distribution(
+ &self,
+ distribution: &RefundDistributionBody,
+ dimensions: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(&distribution.distribution_for)
+ .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()?;
+ }
+
+ query_builder
+ .add_group_by_clause(&distribution.distribution_for)
+ .attach_printable("Error grouping by distribution_for")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ for dim in dimensions.iter() {
+ query_builder.add_outer_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_outer_select_column(&distribution.distribution_for)
+ .switch()?;
+ query_builder.add_outer_select_column("count").switch()?;
+ query_builder
+ .add_outer_select_column("start_bucket")
+ .switch()?;
+ query_builder
+ .add_outer_select_column("end_bucket")
+ .switch()?;
+ let sql_dimensions = query_builder.transform_to_sql_values(dimensions).switch()?;
+
+ query_builder
+ .add_outer_select_column(Window::Sum {
+ field: "count",
+ partition_by: Some(sql_dimensions),
+ order_by: None,
+ alias: Some("total"),
+ })
+ .switch()?;
+
+ query_builder
+ .add_top_n_clause(
+ dimensions,
+ distribution.distribution_cardinality.into(),
+ "count",
+ Order::Descending,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<RefundDistributionRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.refund_status.as_ref().map(|i| i.0.to_string()),
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.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<
+ Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/filters.rs b/crates/analytics/src/refunds/filters.rs
index d87a778ebf3..b742187c4e6 100644
--- a/crates/analytics/src/refunds/filters.rs
+++ b/crates/analytics/src/refunds/filters.rs
@@ -56,4 +56,6 @@ pub struct RefundFilterRow {
pub connector: Option<String>,
pub refund_type: Option<DBEnumWrapper<RefundType>>,
pub profile_id: Option<String>,
+ pub refund_reason: Option<String>,
+ pub refund_error_message: Option<String>,
}
diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs
index c211ea82d7a..57e6511d92c 100644
--- a/crates/analytics/src/refunds/metrics.rs
+++ b/crates/analytics/src/refunds/metrics.rs
@@ -31,6 +31,8 @@ pub struct RefundMetricRow {
pub connector: Option<String>,
pub refund_type: Option<DBEnumWrapper<RefundType>>,
pub profile_id: Option<String>,
+ pub refund_reason: Option<String>,
+ pub refund_error_message: Option<String>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
@@ -122,6 +124,16 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::SessionizedRefundReason => {
+ sessionized_metrics::RefundReason
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundErrorMessage => {
+ sessionized_metrics::RefundErrorMessage
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs
index 07de04c5898..7079993094d 100644
--- a/crates/analytics/src/refunds/metrics/refund_count.rs
+++ b/crates/analytics/src/refunds/metrics/refund_count.rs
@@ -99,6 +99,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
index 6cba5f58fed..3890b8be6e9 100644
--- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
+++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
@@ -107,6 +107,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs
index 642cf70580d..4c3f600b05c 100644
--- a/crates/analytics/src/refunds/metrics/refund_success_count.rs
+++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs
@@ -102,6 +102,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs
index 7b5716ba41a..8ed144999a7 100644
--- a/crates/analytics/src/refunds/metrics/refund_success_rate.rs
+++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs
@@ -97,6 +97,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs
index bb404cd3410..3a5195be6c9 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs
@@ -1,10 +1,14 @@
mod refund_count;
+mod refund_error_message;
mod refund_processed_amount;
+mod refund_reason;
mod refund_success_count;
mod refund_success_rate;
pub(super) use refund_count::RefundCount;
+pub(super) use refund_error_message::RefundErrorMessage;
pub(super) use refund_processed_amount::RefundProcessedAmount;
+pub(super) use refund_reason::RefundReason;
pub(super) use refund_success_count::RefundSuccessCount;
pub(super) use refund_success_rate::RefundSuccessRate;
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
index c77e1f7a52c..20989daca7d 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
@@ -100,6 +100,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
new file mode 100644
index 00000000000..72e32907efb
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_error_message.rs
@@ -0,0 +1,190 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket,
+ ToSql, Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundErrorMessage;
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundErrorMessage
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
+ let mut inner_query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+ inner_query_builder
+ .add_select_column("sum(sign_flag)")
+ .switch()?;
+
+ inner_query_builder
+ .add_custom_filter_clause(
+ RefundDimensions::RefundErrorMessage,
+ "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::RefundSessionized);
+
+ 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(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(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Failure,
+ )
+ .switch()?;
+
+ outer_query_builder
+ .add_custom_filter_clause(
+ RefundDimensions::RefundErrorMessage,
+ "NULL",
+ FilterTypes::IsNotNull,
+ )
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ outer_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 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()?;
+
+ let filtered_dimensions: Vec<&RefundDimensions> = dimensions
+ .iter()
+ .filter(|&&dim| dim != RefundDimensions::RefundErrorMessage)
+ .collect();
+
+ for dim in &filtered_dimensions {
+ outer_query_builder
+ .add_order_by_clause(*dim, Order::Ascending)
+ .attach_printable("Error adding order by clause")
+ .switch()?;
+ }
+
+ outer_query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
index c91938228af..93880824ef9 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
@@ -47,6 +47,12 @@ where
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::Sum {
field: "refund_amount",
@@ -109,6 +115,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
new file mode 100644
index 00000000000..0df28901e8f
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs
@@ -0,0 +1,182 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{
+ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket,
+ ToSql, Window,
+ },
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundReason;
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundReason
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
+ let mut inner_query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+ inner_query_builder
+ .add_select_column("sum(sign_flag)")
+ .switch()?;
+
+ inner_query_builder
+ .add_custom_filter_clause(
+ RefundDimensions::RefundReason,
+ "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::RefundSessionized);
+
+ 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(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_custom_filter_clause(
+ RefundDimensions::RefundReason,
+ "NULL",
+ FilterTypes::IsNotNull,
+ )
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ outer_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 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()?;
+
+ let filtered_dimensions: Vec<&RefundDimensions> = dimensions
+ .iter()
+ .filter(|&&dim| dim != RefundDimensions::RefundReason)
+ .collect();
+
+ for dim in &filtered_dimensions {
+ outer_query_builder
+ .add_order_by_clause(*dim, Order::Ascending)
+ .attach_printable("Error adding order by clause")
+ .switch()?;
+ }
+
+ outer_query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
index 332261a3208..c0bb139c46f 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
@@ -102,6 +102,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
index 35ee0d61b50..e2348d51ad7 100644
--- a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
@@ -97,6 +97,8 @@ where
i.connector.clone(),
i.refund_type.as_ref().map(|i| i.0.to_string()),
i.profile_id.clone(),
+ i.refund_reason.clone(),
+ i.refund_error_message.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
diff --git a/crates/analytics/src/refunds/types.rs b/crates/analytics/src/refunds/types.rs
index 3f22081a69d..c0735557d1c 100644
--- a/crates/analytics/src/refunds/types.rs
+++ b/crates/analytics/src/refunds/types.rs
@@ -42,6 +42,21 @@ where
.attach_printable("Error adding profile id filter")?;
}
+ if !self.refund_reason.is_empty() {
+ builder
+ .add_filter_in_range_clause(RefundDimensions::RefundReason, &self.refund_reason)
+ .attach_printable("Error adding refund reason filter")?;
+ }
+
+ if !self.refund_error_message.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ RefundDimensions::RefundErrorMessage,
+ &self.refund_error_message,
+ )
+ .attach_printable("Error adding refund error message filter")?;
+ }
+
Ok(())
}
}
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 1d91ce17c6a..2a94d528768 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -154,6 +154,7 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for SqlxClien
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for SqlxClient {}
impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}
impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {}
+impl super::refunds::distribution::RefundDistributionAnalytics for SqlxClient {}
impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {}
impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {}
impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {}
@@ -214,6 +215,15 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let refund_error_message: Option<String> =
+ row.try_get("refund_error_message").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),
@@ -235,6 +245,8 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow {
connector,
refund_type,
profile_id,
+ refund_reason,
+ refund_error_message,
total,
count,
start_bucket,
@@ -791,12 +803,88 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let refund_error_message: Option<String> =
+ row.try_get("refund_error_message").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
Ok(Self {
currency,
refund_status,
connector,
refund_type,
profile_id,
+ refund_reason,
+ refund_error_message,
+ })
+ }
+}
+
+impl<'a> FromRow<'a, PgRow> for super::refunds::distribution::RefundDistributionRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let currency: Option<DBEnumWrapper<Currency>> =
+ row.try_get("currency").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let refund_status: Option<DBEnumWrapper<RefundStatus>> =
+ row.try_get("refund_status").or_else(|e| match e {
+ 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 refund_type: Option<DBEnumWrapper<RefundType>> =
+ row.try_get("refund_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let profile_id: Option<String> = row.try_get("profile_id").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),
+ })?;
+ let count: Option<i64> = row.try_get("count").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let refund_reason: Option<String> = row.try_get("refund_reason").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let refund_error_message: Option<String> =
+ row.try_get("refund_error_message").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")?
+ .and_then(|dt| dt.replace_millisecond(0).ok());
+ let end_bucket: Option<PrimitiveDateTime> = row
+ .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
+ .and_then(|dt| dt.replace_millisecond(0).ok());
+ Ok(Self {
+ currency,
+ refund_status,
+ connector,
+ refund_type,
+ profile_id,
+ total,
+ count,
+ refund_reason,
+ refund_error_message,
+ start_bucket,
+ end_bucket,
})
}
}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index b6d4044c5f3..806eb4b6e0e 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -12,7 +12,7 @@ use self::{
frm::{FrmDimensions, FrmMetrics},
payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics},
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
- refunds::{RefundDimensions, RefundMetrics},
+ refunds::{RefundDimensions, RefundDistributions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
};
pub mod active_payments;
@@ -73,7 +73,7 @@ pub struct GetPaymentMetricRequest {
#[serde(default)]
pub filters: payments::PaymentFilters,
pub metrics: HashSet<PaymentMetrics>,
- pub distribution: Option<Distribution>,
+ pub distribution: Option<PaymentDistributionBody>,
#[serde(default)]
pub delta: bool,
}
@@ -98,11 +98,18 @@ impl Into<u64> for QueryLimit {
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct Distribution {
+pub struct PaymentDistributionBody {
pub distribution_for: PaymentDistributions,
pub distribution_cardinality: QueryLimit,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RefundDistributionBody {
+ pub distribution_for: RefundDistributions,
+ pub distribution_cardinality: QueryLimit,
+}
+
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
@@ -142,6 +149,7 @@ pub struct GetRefundMetricRequest {
#[serde(default)]
pub filters: refunds::RefundFilters,
pub metrics: HashSet<RefundMetrics>,
+ pub distribution: Option<RefundDistributionBody>,
#[serde(default)]
pub delta: bool,
}
@@ -230,8 +238,12 @@ pub struct PaymentIntentsAnalyticsMetadata {
#[derive(Debug, serde::Serialize)]
pub struct RefundsAnalyticsMetadata {
+ pub total_refund_success_rate: Option<f64>,
pub total_refund_processed_amount: Option<u64>,
pub total_refund_processed_amount_in_usd: Option<u64>,
+ pub total_refund_processed_count: Option<u64>,
+ pub total_refund_reason_count: Option<u64>,
+ pub total_refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs
index d981bd4382f..0afca6c1ef6 100644
--- a/crates/api_models/src/analytics/refunds.rs
+++ b/crates/api_models/src/analytics/refunds.rs
@@ -43,6 +43,10 @@ pub struct RefundFilters {
pub refund_type: Vec<RefundType>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
+ #[serde(default)]
+ pub refund_reason: Vec<String>,
+ #[serde(default)]
+ pub refund_error_message: Vec<String>,
}
#[derive(
@@ -67,6 +71,8 @@ pub enum RefundDimensions {
Connector,
RefundType,
ProfileId,
+ RefundReason,
+ RefundErrorMessage,
}
#[derive(
@@ -92,6 +98,44 @@ pub enum RefundMetrics {
SessionizedRefundCount,
SessionizedRefundSuccessCount,
SessionizedRefundProcessedAmount,
+ SessionizedRefundReason,
+ SessionizedRefundErrorMessage,
+}
+
+#[derive(Debug, Default, serde::Serialize)]
+pub struct ReasonsResult {
+ pub reason: String,
+ pub count: i64,
+ pub percentage: f64,
+}
+
+#[derive(Debug, Default, serde::Serialize)]
+pub struct ErrorMessagesResult {
+ pub error_message: String,
+ pub count: i64,
+ pub percentage: f64,
+}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Hash,
+ PartialEq,
+ Eq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumIter,
+ strum::AsRefStr,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum RefundDistributions {
+ #[strum(serialize = "refund_reason")]
+ SessionizedRefundReason,
+ #[strum(serialize = "refund_error_message")]
+ SessionizedRefundErrorMessage,
}
pub mod metric_behaviour {
@@ -124,9 +168,10 @@ pub struct RefundMetricsBucketIdentifier {
pub currency: Option<Currency>,
pub refund_status: Option<String>,
pub connector: Option<String>,
-
pub refund_type: Option<String>,
pub profile_id: Option<String>,
+ pub refund_reason: Option<String>,
+ pub refund_error_message: Option<String>,
#[serde(rename = "time_range")]
pub time_bucket: TimeRange,
#[serde(rename = "time_bucket")]
@@ -141,6 +186,8 @@ impl Hash for RefundMetricsBucketIdentifier {
self.connector.hash(state);
self.refund_type.hash(state);
self.profile_id.hash(state);
+ self.refund_reason.hash(state);
+ self.refund_error_message.hash(state);
self.time_bucket.hash(state);
}
}
@@ -155,12 +202,15 @@ impl PartialEq for RefundMetricsBucketIdentifier {
}
impl RefundMetricsBucketIdentifier {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
currency: Option<Currency>,
refund_status: Option<String>,
connector: Option<String>,
refund_type: Option<String>,
profile_id: Option<String>,
+ refund_reason: Option<String>,
+ refund_error_message: Option<String>,
normalized_time_range: TimeRange,
) -> Self {
Self {
@@ -169,6 +219,8 @@ impl RefundMetricsBucketIdentifier {
connector,
refund_type,
profile_id,
+ refund_reason,
+ refund_error_message,
time_bucket: normalized_time_range,
start_time: normalized_time_range.start_time,
}
@@ -176,11 +228,18 @@ impl RefundMetricsBucketIdentifier {
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketValue {
+ pub successful_refunds: Option<u32>,
+ pub total_refunds: Option<u32>,
pub refund_success_rate: Option<f64>,
pub refund_count: Option<u64>,
pub refund_success_count: Option<u64>,
pub refund_processed_amount: Option<u64>,
pub refund_processed_amount_in_usd: Option<u64>,
+ pub refund_processed_count: Option<u64>,
+ pub refund_reason_distribution: Option<Vec<ReasonsResult>>,
+ pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>,
+ pub refund_reason_count: Option<u64>,
+ pub refund_error_message_count: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketResponse {
|
2024-11-19T17:04:47Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Adding metrics, and support for Refund Page in Analytics V2 Dashboard through sessionizer.
The metrics added are as follows:
- **Static Metrics in overview section:**
- Refund Success Rate
- Total Refunds Processed (Amount)
- Successful Refunds
- Failed Refunds
- Pending Refunds
- **Series Graphs:**
- Refunds Processed (Amount and Count) (With granularity)
- Refunds Success Rate (With granularity)
- **Distributions:**
- Successful Refunds by connector
- Failed Refunds by connector
- **Tables**
- Refund Reasons
- Failed Refund Error Message
- Failed Refund Error Reasons
This PR also adds support for refunds distribution, similar to payments distribution, which may be needed in the future for more advanced analytics.
The following distributions are added:
- Refund Reasons
- Refund Error Message
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Provide more insights into Refunds data for the merchants to make important business 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)?
-->
Refunds Success Rate:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"source": "BATCH",
"metrics": [
"sessionized_refund_success_rate"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": 6,
"total_refunds": 10,
"refund_success_rate": 60.0,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": 60.0,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"successful_refunds": 6,
"total_refunds": 10,
"refund_success_rate": 60.0,
```
- metaData:
```json
"total_refund_success_rate": 60.0,
```
Total Refunds Processed (Amount)
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"source": "BATCH",
"metrics": [
"sessionized_refund_processed_amount"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 1800,
"refund_processed_amount_in_usd": 21,
"refund_processed_count": 3,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": "INR",
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 1800,
"refund_processed_amount_in_usd": 1800,
"refund_processed_count": 3,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": "USD",
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 3600,
"total_refund_processed_amount_in_usd": 1821,
"total_refund_processed_count": 6,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_processed_amount": 1800,
"refund_processed_amount_in_usd": 21,
"refund_processed_count": 3,
```
- metaData:
```json
"total_refund_processed_amount": 3600,
"total_refund_processed_amount_in_usd": 1821,
"total_refund_processed_count": 6,
```
Successful Refunds:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"filters": {
"refund_status": [
"success"
]
},
"source": "BATCH",
"metrics": [
"sessionized_refund_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 6,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_count": 6,
```
Failed Refunds
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"filters": {
"refund_status": [
"failure"
]
},
"source": "BATCH",
"metrics": [
"sessionized_refund_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 4,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_count": 4,
```
Pending Refunds
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"filters": {
"refund_status": [
"pending"
]
},
"source": "BATCH",
"metrics": [
"sessionized_refund_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 0,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_count": 0,
```
Refund Success Rate series graph is similar to Refund Success Rate above, granularity will be added.
Refund Processed Amount and Count series graph is similar to the one above, granularity will be added.
Successful Refunds Distribution by connector:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector"
],
"source": "BATCH",
"metrics": [
"sessionized_refund_count",
"sessionized_refund_success_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 7,
"refund_success_count": 6,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 3,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested and taken into account:
- queryData:
```json
"refund_count": 7,
"refund_success_count": 6,
"connector": "stripe_test",
```
Failed Refunds Distribution by connector:
- This will have multiple API calls from FE, and data would be calculated at FE only.
- First Request:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector"
],
"source": "BATCH",
"metrics": [
"sessionized_refund_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 7,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 3,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested and taken into account:
- queryData:
```json
"refund_count": 7,
"connector": "stripe_test",
```
- Second Request:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"filters": {
"refund_status": [
"failure"
]
},
"groupByNames": [
"connector"
],
"source": "BATCH",
"metrics": [
"sessionized_refund_count"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 3,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": 1,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested and taken into account:
- queryData:
```json
"refund_count": 1,
"connector": "stripe_test",
```
From the two API calls, failed refunds and total refunds can be calculated for every connector, and the failed refunds distribution can be plotted and displayed.
Refund Reasons:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector", "refund_reason"
],
"source": "BATCH",
"metrics": [
"sessionized_refund_reason"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 1,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test REFUND - 1",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 6,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": "Customer returned product",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 1,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 3",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 2,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 2",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 10,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_reason_count": 1,
"refund_reason": "Test Refund - 3",
"connector": "stripe_test",
```
- metaData:
```json
"total_refund_reason_count": 10,
```
Failed Refund Reasons:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector", "refund_reason"
],
"filters": {
"refund_status": ["failure"]
},
"source": "BATCH",
"metrics": [
"sessionized_refund_reason"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 2,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 2",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 1,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": "Customer returned product",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 1,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 3",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 4,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_reason_count": 1,
"refund_reason": "Test Refund - 3",
"connector": "adyen",
```
- metaData:
```json
"total_refund_reason_count": 4,
```
Failed Refund Error Message:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector", "refund_error_message"
],
"source": "BATCH",
"metrics": [
"sessionized_refund_error_message"
],
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 1,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": "The refund failed due to test-failure 3.",
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 1,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": "The refund failed due to test-failure.",
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 2
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_error_message_count": 1,
"refund_error_message": "The refund failed due to test-failure.",
"connector": "adyen",
```
- metaData:
```json
"total_refund_error_message_count": 2
```
Refund Reasons Distribution:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector"
],
"distribution": {
"distributionFor": "sessionized_refund_reason",
"distributionCardinality": "TOP_5"
},
"metrics": [
],
"source": "BATCH",
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": [
{
"reason": "Test REFUND - 1",
"count": 1,
"percentage": 14.29
}
],
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test REFUND - 1",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": [
{
"reason": "Test Refund - 2",
"count": 2,
"percentage": 66.67
}
],
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 2",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": [
{
"reason": "Test Refund - 3",
"count": 1,
"percentage": 33.33
}
],
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": "Test Refund - 3",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": [
{
"reason": "Customer returned product",
"count": 6,
"percentage": 85.71
}
],
"refund_error_message_distribution": null,
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": "Customer returned product",
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_reason_distribution": [
{
"reason": "Test REFUND - 1",
"count": 1,
"percentage": 14.29
}
],
"connector": "stripe_test",
```
Refund Error Message Distribution:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjk3MjQxOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.eWEvxPl_3-C8tv5_uDfyqV8B8DDUeTK4yn-IHnIQvwY' \
--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-11-01T09:00:00Z",
"endTime": "2024-11-29T09:30:39Z"
},
"groupByNames": [
"connector"
],
"distribution": {
"distributionFor": "sessionized_refund_error_message",
"distributionCardinality": "TOP_5"
},
"metrics": [
],
"source": "BATCH",
"delta": true
}
]'
```
Response:
```json
{
"queryData": [
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": [
{
"error_message": "The refund failed due to test-failure 3.",
"count": 1,
"percentage": 33.33
}
],
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": "The refund failed due to test-failure 3.",
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": [
{
"error_message": "",
"count": 1,
"percentage": 33.33
}
],
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": [
{
"error_message": "The refund failed due to test-failure.",
"count": 1,
"percentage": 33.33
}
],
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "adyen",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": "The refund failed due to test-failure.",
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
},
{
"successful_refunds": null,
"total_refunds": null,
"refund_success_rate": null,
"refund_count": null,
"refund_success_count": null,
"refund_processed_amount": 0,
"refund_processed_amount_in_usd": null,
"refund_processed_count": null,
"refund_reason_distribution": null,
"refund_error_message_distribution": [
{
"error_message": "",
"count": 1,
"percentage": 100.0
}
],
"refund_reason_count": 0,
"refund_error_message_count": 0,
"currency": null,
"refund_status": null,
"connector": "stripe_test",
"refund_type": null,
"profile_id": null,
"refund_reason": null,
"refund_error_message": null,
"time_range": {
"start_time": "2024-11-01T09:00:00.000Z",
"end_time": "2024-11-29T09:30:39.000Z"
},
"time_bucket": "2024-11-01 09:00:00"
}
],
"metaData": [
{
"total_refund_success_rate": null,
"total_refund_processed_amount": 0,
"total_refund_processed_amount_in_usd": 0,
"total_refund_processed_count": 0,
"total_refund_reason_count": 0,
"total_refund_error_message_count": 0
}
]
}
```
Fields to be tested:
- queryData:
```json
"refund_error_message_distribution": [
{
"error_message": "The refund failed due to test-failure 3.",
"count": 1,
"percentage": 33.33
}
],
"connector": "adyen",
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
64383915bda5693df1cecf6cc5683e8b9aaef99b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6592
|
Bug: refactor(users): Force 2FA in prod env
Currently 2FA is not forced on prod, users have ability to skip it.
For the PCI compliance, we have to force users to setup and use 2FA.
|
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 73e5794f042..76f42085f92 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -149,7 +149,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Production"
base_url = "https://live.hyperswitch.io"
-force_two_factor_auth = false
+force_two_factor_auth = true
[frm]
enabled = false
|
2024-11-18T11:01:56Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR forces users to use 2FA in production.
### 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/deployments/production.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 #6592.
## How did you test 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 change will only affect production.
1. 2FA Status API
- `is_skippable` field is added in the response.
```
curl --location 'http://localhost:8080/user/2fa/v2' \
--header 'Authorization: JWT' \
```
```
{
"status": null,
"is_skippable": true
}
```
2. Terminate 2FA API
- This API will now not allow skip 2FA if the `force_two_factor_auth`
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: JWT' \
```
```
{
"error": {
"type": "invalid_request",
"message": "Two factor auth required",
"code": "UR_40"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d32397f060731f51a15634e221117a554b8b3721
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6580
|
Bug: chore(infra): SDK Table schema sanity
Editing SDK Tables schema in the codebase for end to end ( ingestion to querying on dashboard ) sanity
|
diff --git a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql
index bfe6401cacc..c5c70cc9e66 100644
--- a/crates/analytics/docs/clickhouse/scripts/sdk_events.sql
+++ b/crates/analytics/docs/clickhouse/scripts/sdk_events.sql
@@ -6,7 +6,7 @@ CREATE TABLE sdk_events_queue (
`event_name` LowCardinality(Nullable(String)),
`first_event` LowCardinality(Nullable(String)),
`latency` Nullable(UInt32),
- `timestamp` String,
+ `timestamp` DateTime64(3),
`browser_name` LowCardinality(Nullable(String)),
`browser_version` Nullable(String),
`platform` LowCardinality(Nullable(String)),
@@ -115,7 +115,8 @@ CREATE TABLE sdk_events_audit (
`remote_ip` Nullable(String),
`log_type` LowCardinality(Nullable(String)),
`event_name` LowCardinality(Nullable(String)),
- `first_event` Bool DEFAULT 1,
+ `first_event` Bool,
+ `latency` Nullable(UInt32),
`browser_name` LowCardinality(Nullable(String)),
`browser_version` Nullable(String),
`platform` LowCardinality(Nullable(String)),
@@ -125,10 +126,10 @@ CREATE TABLE sdk_events_audit (
`value` Nullable(String),
`component` LowCardinality(Nullable(String)),
`payment_method` LowCardinality(Nullable(String)),
- `payment_experience` LowCardinality(Nullable(String)) DEFAULT '',
- `created_at` DateTime64(3) DEFAULT now64() CODEC(T64, LZ4),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `latency` Nullable(UInt32) DEFAULT 0
+ `payment_experience` LowCardinality(Nullable(String)),
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `created_at_precise` DateTime64(3),
+ `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4)
) ENGINE = MergeTree PARTITION BY merchant_id
ORDER BY
(merchant_id, payment_id)
@@ -156,7 +157,7 @@ WHERE
length(_error) > 0;
CREATE MATERIALIZED VIEW sdk_events_audit_mv TO sdk_events_audit (
- `payment_id` Nullable(String),
+ `payment_id` String,
`merchant_id` String,
`remote_ip` Nullable(String),
`log_type` LowCardinality(Nullable(String)),
|
2024-11-14T16:36:06Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Updating SDK table schema
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
crates/analytics/docs/clickhouse/scripts/sdk_events.sql
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This resolves the issue people face for SDK Events table API on dashboard is using the sdk_events_audit table
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Schema structure changes for sdk table. Nothing to test.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
15f873bd1296169149987041f4008b0afe2ac2aa
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6577
|
Bug: [BUG] FATAL: role "root" does not exist
### Bug Description
Whenever hyperswitch-pg-1 sever running in docker-compose, it though an error " role "root" does not exist"
### Expected Behavior
Error should not come.
### Actual Behavior

### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Open Docker Desktop
2. Run hyperswitch-pg-1 server
3. After some time, you will see the error
### Context For The Bug
While setting hyperswitch on my local machine, I came across this error.
### 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: Ubuntu 24.04
2. Rust version (output of `rustc --version`): ``: rustc 1.82.0 (f6e511eec 2024-10-15)
3. App version (output of `cargo r --features vergen -- --version`): `` NA
### 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 07a2131c6d4..d7a0e365c36 100644
--- a/docker-compose-development.yml
+++ b/docker-compose-development.yml
@@ -26,7 +26,7 @@ services:
- POSTGRES_PASSWORD=db_pass
- POSTGRES_DB=hyperswitch_db
healthcheck:
- test: ["CMD-SHELL", "pg_isready"]
+ test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
interval: 5s
retries: 3
start_period: 5s
diff --git a/docker-compose.yml b/docker-compose.yml
index f766ff91053..7450a650119 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -21,7 +21,7 @@ services:
- POSTGRES_PASSWORD=db_pass
- POSTGRES_DB=hyperswitch_db
healthcheck:
- test: ["CMD-SHELL", "pg_isready"]
+ test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
interval: 5s
retries: 3
start_period: 5s
|
2024-11-15T08:47:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6577.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0805a937b1bc12ac1dfb23922036733ed971a87a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6574
|
Bug: feat(analytics): add `smart_retries` only metrics
## Proposed changes
There should be fields in PaymentDistribution, for the case where we only want to extract metric for Subsequent smart retried attempts.
For example, we have `success_rate` and `success_rate_without_retries`
Now missing field is `success_rate_with_only_smart_retries`.
This change should be extended to all fields
|
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index 651eeb0bcfe..c4e48300d07 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -76,8 +76,11 @@ pub struct PaymentsDistributionAccumulator {
pub failed: u32,
pub total: u32,
pub success_without_retries: u32,
+ pub success_with_only_retries: u32,
pub failed_without_retries: u32,
+ pub failed_with_only_retries: u32,
pub total_without_retries: u32,
+ pub total_with_only_retries: u32,
}
pub trait PaymentMetricAccumulator {
@@ -181,7 +184,14 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator {
}
impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
- type MetricOutput = (Option<f64>, Option<f64>, Option<f64>, Option<f64>);
+ type MetricOutput = (
+ Option<f64>,
+ Option<f64>,
+ Option<f64>,
+ Option<f64>,
+ Option<f64>,
+ Option<f64>,
+ );
fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
if let Some(ref status) = metrics.status {
@@ -193,6 +203,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
self.success += success;
if metrics.first_attempt.unwrap_or(false) {
self.success_without_retries += success;
+ } else {
+ self.success_with_only_retries += success;
}
}
}
@@ -201,6 +213,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
self.failed += failed;
if metrics.first_attempt.unwrap_or(false) {
self.failed_without_retries += failed;
+ } else {
+ self.failed_with_only_retries += failed;
}
}
}
@@ -208,6 +222,8 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
self.total += total;
if metrics.first_attempt.unwrap_or(false) {
self.total_without_retries += total;
+ } else {
+ self.total_with_only_retries += total;
}
}
}
@@ -215,14 +231,17 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
fn collect(self) -> Self::MetricOutput {
if self.total == 0 {
- (None, None, None, None)
+ (None, None, None, None, None, None)
} else {
let success = Some(self.success);
let success_without_retries = Some(self.success_without_retries);
+ let success_with_only_retries = Some(self.success_with_only_retries);
let failed = Some(self.failed);
+ let failed_with_only_retries = Some(self.failed_with_only_retries);
let failed_without_retries = Some(self.failed_without_retries);
let total = Some(self.total);
let total_without_retries = Some(self.total_without_retries);
+ let total_with_only_retries = Some(self.total_with_only_retries);
let success_rate = match (success, total) {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
@@ -235,6 +254,12 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
_ => None,
};
+ let success_rate_with_only_retries =
+ match (success_with_only_retries, total_with_only_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,
@@ -245,11 +270,19 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator {
(Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
_ => None,
};
+
+ let failed_rate_with_only_retries =
+ match (failed_with_only_retries, total_with_only_retries) {
+ (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)),
+ _ => None,
+ };
(
success_rate,
success_rate_without_retries,
+ success_rate_with_only_retries,
failed_rate,
failed_rate_without_retries,
+ failed_rate_with_only_retries,
)
}
}
@@ -393,8 +426,10 @@ impl PaymentMetricsAccumulator {
let (
payments_success_rate_distribution,
payments_success_rate_distribution_without_smart_retries,
+ payments_success_rate_distribution_with_only_retries,
payments_failure_rate_distribution,
payments_failure_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution_with_only_retries,
) = self.payments_distribution.collect();
let (failure_reason_count, failure_reason_count_without_smart_retries) =
self.failure_reasons_distribution.collect();
@@ -413,8 +448,10 @@ impl PaymentMetricsAccumulator {
connector_success_rate: self.connector_success_rate.collect(),
payments_success_rate_distribution,
payments_success_rate_distribution_without_smart_retries,
+ payments_success_rate_distribution_with_only_retries,
payments_failure_rate_distribution,
payments_failure_rate_distribution_without_smart_retries,
+ payments_failure_rate_distribution_with_only_retries,
failure_reason_count,
failure_reason_count_without_smart_retries,
payment_processed_amount_usd,
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index 1faba79eb37..70b1da62bea 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -283,8 +283,10 @@ pub struct PaymentMetricsBucketValue {
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_success_rate_distribution_with_only_retries: Option<f64>,
pub payments_failure_rate_distribution: Option<f64>,
pub payments_failure_rate_distribution_without_smart_retries: Option<f64>,
+ pub payments_failure_rate_distribution_with_only_retries: Option<f64>,
pub failure_reason_count: Option<u64>,
pub failure_reason_count_without_smart_retries: Option<u64>,
}
|
2024-11-14T13:37:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added support for calculating new metrics based on smart retries for Analytics v2 dashboard.
The 2 metrics are:
- Payment Processed Amount and Count for smart retries
- Payments Success Rate and Failure Rate distribution for Smart Retries
`Payment Processed Amount and Count for Smart Retries` can be calculated with the existing metrics, with just a subtraction of `payment_processed_amount_without_smart_retries` from `payment_processed_amount`, hence doesn't require a separate metric.
In the `PaymentDistributionAccumulator`, I added another field variant with the signature
`<field_name>_with_only_smart_retries`.
Where `field_name` can be anything from `success_rate`, `failure_rate`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6574
## How did you test 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
- Hit the curl:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStat' \
--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/130.0.0.0 Safari/537.36' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-11-07T01:30:00Z",
"endTime": "2024-11-09T23:30:00Z"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"payments_distribution"
],
"delta": true
}
]'
```
### Response
```json
{
"queryData": [
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 0,
"payment_processed_amount_usd": null,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_amount_without_smart_retries_usd": null,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": 66.66666666666667,
"payments_success_rate_distribution_without_smart_retries": 57.142857142857146,
"payments_success_rate_distribution_with_only_retries": 100.0,
"payments_failure_rate_distribution": 33.333333333333336,
"payments_failure_rate_distribution_without_smart_retries": 42.857142857142854,
"payments_failure_rate_distribution_with_only_retries": 0.0,
"failure_reason_count": 0,
"failure_reason_count_without_smart_retries": 0,
"currency": null,
"status": null,
"connector": null,
"authentication_type": null,
"payment_method": null,
"payment_method_type": null,
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": null,
"time_range": {
"start_time": "2024-11-07T01:30:00.000Z",
"end_time": "2024-11-09T23:30:00.000Z"
},
"time_bucket": "2024-11-07 01:30:00"
}
],
"metaData": [
{
"total_payment_processed_amount": 0,
"total_payment_processed_amount_usd": 0,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_amount_without_smart_retries_usd": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0,
"total_failure_reasons_count": 0,
"total_failure_reasons_count_without_smart_retries": 0
}
]
}
```
Fields that are required to be checked:
`queryData`:
```json
"payments_success_rate_distribution_with_only_retries": 100.0,
"payments_failure_rate_distribution_with_only_retries": 0.0,
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8cc5d3db9afb120b00115c6714be2e362951cc94
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6597
|
Bug: [FEATURE] Xendit Template PR
### Feature Description
Template code added for new connector Xendit
https://developers.xendit.co/api-reference
### Possible Implementation
Template code added for new connector Xendit
https://developers.xendit.co/api-reference
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index d2fa50d8629..96c6a037ad3 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -18092,6 +18092,7 @@
"wise",
"worldline",
"worldpay",
+ "xendit",
"zen",
"plaid",
"zsl"
diff --git a/config/config.example.toml b/config/config.example.toml
index 289087f4a33..08a32035c4b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -271,6 +271,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
zsl.base_url = "https://api.sitoffalb.net/"
zen.base_url = "https://api.zen-test.com/"
zen.secondary_base_url = "https://secure.zen-test.com/"
@@ -329,6 +330,7 @@ cards = [
"threedsecureio",
"thunes",
"worldpay",
+ "xendit",
"zen",
"zsl",
]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 1c7a40ea539..e1ea99bc8d1 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -111,6 +111,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
zen.base_url = "https://api.zen-test.com/"
zen.secondary_base_url = "https://secure.zen-test.com/"
zsl.base_url = "https://api.sitoffalb.net/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 73e5794f042..434b20524f0 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -115,6 +115,7 @@ wellsfargopayout.base_url = "https://api.wellsfargo.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
zen.base_url = "https://api.zen.com/"
zen.secondary_base_url = "https://secure.zen.com/"
zsl.base_url = "https://apirh.prodoffalb.net/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 98e1e7e00d9..4421d1b1e96 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -115,6 +115,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
zen.base_url = "https://api.zen-test.com/"
zen.secondary_base_url = "https://secure.zen-test.com/"
zsl.base_url = "https://api.sitoffalb.net/"
diff --git a/config/development.toml b/config/development.toml
index b6638fe1d47..adad850c4d6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -169,6 +169,7 @@ cards = [
"wise",
"worldline",
"worldpay",
+ "xendit",
"zen",
"zsl",
]
@@ -279,6 +280,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
tsys.base_url = "https://stagegw.transnox.com/"
volt.base_url = "https://api.sandbox.volt.io/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 7adeee8a376..445205c12fe 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -201,6 +201,7 @@ wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
zen.base_url = "https://api.zen-test.com/"
zen.secondary_base_url = "https://secure.zen-test.com/"
zsl.base_url = "https://api.sitoffalb.net/"
@@ -287,6 +288,7 @@ cards = [
"wise",
"worldline",
"worldpay",
+ "xendit",
"zen",
"zsl",
]
diff --git a/crates/api_models/src/connector_enums.rs b/crates/api_models/src/connector_enums.rs
index 77081f49957..11b38400920 100644
--- a/crates/api_models/src/connector_enums.rs
+++ b/crates/api_models/src/connector_enums.rs
@@ -129,6 +129,7 @@ pub enum Connector {
Signifyd,
Plaid,
Riskified,
+ // Xendit,
Zen,
Zsl,
}
@@ -259,6 +260,7 @@ impl Connector {
| Self::Wise
| Self::Worldline
| Self::Worldpay
+ // | Self::Xendit
| Self::Zen
| Self::Zsl
| Self::Signifyd
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 9beaed75960..e75a4038c07 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -123,6 +123,7 @@ pub enum RoutableConnectors {
Wise,
Worldline,
Worldpay,
+ Xendit,
Zen,
Plaid,
Zsl,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 3634fe730ca..b1cf0bd9f9c 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -231,6 +231,7 @@ pub struct ConnectorConfig {
pub wise_payout: Option<ConnectorTomlConfig>,
pub worldline: Option<ConnectorTomlConfig>,
pub worldpay: Option<ConnectorTomlConfig>,
+ pub xendit: Option<ConnectorTomlConfig>,
pub square: Option<ConnectorTomlConfig>,
pub stax: Option<ConnectorTomlConfig>,
pub dummy_connector: Option<ConnectorTomlConfig>,
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 2bc82450096..b764ab5b441 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -36,6 +36,7 @@ pub mod tsys;
pub mod volt;
pub mod worldline;
pub mod worldpay;
+pub mod xendit;
pub mod zen;
pub mod zsl;
@@ -48,5 +49,5 @@ pub use self::{
nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, payeezy::Payeezy,
payu::Payu, powertranz::Powertranz, razorpay::Razorpay, shift4::Shift4, square::Square,
stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline,
- worldpay::Worldpay, zen::Zen, zsl::Zsl,
+ worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/xendit.rs b/crates/hyperswitch_connectors/src/connectors/xendit.rs
new file mode 100644
index 00000000000..c3f75a7673e
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/xendit.rs
@@ -0,0 +1,563 @@
+pub mod transformers;
+
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+ types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
+ RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundSyncRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation},
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{self, Response},
+ webhooks,
+};
+use masking::{ExposeInterface, Mask};
+use transformers as xendit;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Xendit {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Xendit {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Xendit {}
+impl api::PaymentSession for Xendit {}
+impl api::ConnectorAccessToken for Xendit {}
+impl api::MandateSetup for Xendit {}
+impl api::PaymentAuthorize for Xendit {}
+impl api::PaymentSync for Xendit {}
+impl api::PaymentCapture for Xendit {}
+impl api::PaymentVoid for Xendit {}
+impl api::Refund for Xendit {}
+impl api::RefundExecute for Xendit {}
+impl api::RefundSync for Xendit {}
+impl api::PaymentToken for Xendit {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Xendit
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Xendit
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Xendit {
+ fn id(&self) -> &'static str {
+ "xendit"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ // TODO! Check connector documentation, on which unit they are processing the currency.
+ // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
+ // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.xendit.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = xendit::XenditAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: xendit::XenditErrorResponse = res
+ .response
+ .parse_struct("XenditErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Xendit {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Xendit {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Xendit {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Xendit {}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Xendit {
+ fn get_headers(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = xendit::XenditRouterData::from((amount, req));
+ let connector_req = xendit::XenditPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: xendit::XenditPaymentsResponse = res
+ .response
+ .parse_struct("Xendit PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Xendit {
+ fn get_headers(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: xendit::XenditPaymentsResponse = res
+ .response
+ .parse_struct("xendit PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Xendit {
+ fn get_headers(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: xendit::XenditPaymentsResponse = res
+ .response
+ .parse_struct("Xendit PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Xendit {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Xendit {
+ fn get_headers(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let refund_amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = xendit::XenditRouterData::from((refund_amount, req));
+ let connector_req = xendit::XenditRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundsRouterData<Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
+ let response: xendit::RefundResponse =
+ res.response
+ .parse_struct("xendit RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Xendit {
+ fn get_headers(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
+ let response: xendit::RefundResponse = res
+ .response
+ .parse_struct("xendit RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl webhooks::IncomingWebhook for Xendit {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
new file mode 100644
index 00000000000..c9d4cd2583c
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
@@ -0,0 +1,228 @@
+use common_enums::enums;
+use common_utils::types::StringMinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::errors;
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::PaymentsAuthorizeRequestData,
+};
+
+//TODO: Fill the struct with respective fields
+pub struct XenditRouterData<T> {
+ pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> From<(StringMinorUnit, T)> for XenditRouterData<T> {
+ fn from((amount, item): (StringMinorUnit, T)) -> Self {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Self {
+ amount,
+ router_data: item,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, PartialEq)]
+pub struct XenditPaymentsRequest {
+ amount: StringMinorUnit,
+ card: XenditCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct XenditCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&XenditRouterData<&PaymentsAuthorizeRouterData>> for XenditPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &XenditRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = XenditCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.clone(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct XenditAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for XenditAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum XenditPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<XenditPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: XenditPaymentStatus) -> Self {
+ match item {
+ XenditPaymentStatus::Succeeded => Self::Charged,
+ XenditPaymentStatus::Failed => Self::Failure,
+ XenditPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct XenditPaymentsResponse {
+ status: XenditPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, XenditPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, XenditPaymentsResponse, T, PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: common_enums::AttemptStatus::from(item.response.status),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct XenditRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&XenditRouterData<&RefundsRouterData<F>>> for XenditRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &XenditRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct XenditErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 6ee8926f8df..bc86e713501 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -126,6 +126,7 @@ default_imp_for_authorize_session_token!(
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -182,6 +183,7 @@ default_imp_for_calculate_tax!(
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -234,6 +236,7 @@ default_imp_for_session_update!(
connectors::Globepay,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl,
connectors::Powertranz,
@@ -291,6 +294,7 @@ default_imp_for_post_session_tokens!(
connectors::Globepay,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Powertranz,
connectors::Thunes,
connectors::Tsys,
@@ -346,6 +350,7 @@ default_imp_for_complete_authorize!(
connectors::Tsys,
connectors::Worldline,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -404,6 +409,7 @@ default_imp_for_incremental_authorization!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -461,6 +467,7 @@ default_imp_for_create_customer!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -515,6 +522,7 @@ default_imp_for_connector_redirect_response!(
connectors::Tsys,
connectors::Worldline,
connectors::Volt,
+ connectors::Xendit,
connectors::Zsl
);
@@ -569,6 +577,7 @@ default_imp_for_pre_processing_steps!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -627,6 +636,7 @@ default_imp_for_post_processing_steps!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -685,6 +695,7 @@ default_imp_for_approve!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -743,6 +754,7 @@ default_imp_for_reject!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -801,6 +813,7 @@ default_imp_for_webhook_source_verification!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -860,6 +873,7 @@ default_imp_for_accept_dispute!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -918,6 +932,7 @@ default_imp_for_submit_evidence!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -976,6 +991,7 @@ default_imp_for_defend_dispute!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1043,6 +1059,7 @@ default_imp_for_file_upload!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1093,6 +1110,7 @@ default_imp_for_payouts!(
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1153,6 +1171,7 @@ default_imp_for_payouts_create!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1213,6 +1232,7 @@ default_imp_for_payouts_retrieve!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1273,6 +1293,7 @@ default_imp_for_payouts_eligibility!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1333,6 +1354,7 @@ default_imp_for_payouts_fulfill!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1393,6 +1415,7 @@ default_imp_for_payouts_cancel!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1453,6 +1476,7 @@ default_imp_for_payouts_quote!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1513,6 +1537,7 @@ default_imp_for_payouts_recipient!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1573,6 +1598,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1633,6 +1659,7 @@ default_imp_for_frm_sale!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1693,6 +1720,7 @@ default_imp_for_frm_checkout!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1753,6 +1781,7 @@ default_imp_for_frm_transaction!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1813,6 +1842,7 @@ default_imp_for_frm_fulfillment!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1873,6 +1903,7 @@ default_imp_for_frm_record_return!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1930,6 +1961,7 @@ default_imp_for_revoking_mandates!(
connectors::Worldline,
connectors::Worldpay,
connectors::Volt,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index d747d65d73a..75cbf192e55 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -243,6 +243,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -302,6 +303,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -356,6 +358,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -416,6 +419,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -475,6 +479,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -534,6 +539,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -603,6 +609,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -664,6 +671,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -725,6 +733,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -786,6 +795,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -847,6 +857,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -908,6 +919,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -969,6 +981,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1030,6 +1043,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1091,6 +1105,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1150,6 +1165,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1211,6 +1227,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1272,6 +1289,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1333,6 +1351,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1394,6 +1413,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1455,6 +1475,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
@@ -1513,6 +1534,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Xendit,
connectors::Zen,
connectors::Zsl
);
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index 58810a0cb34..5e5eeea31b3 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -92,6 +92,7 @@ pub struct Connectors {
pub wise: ConnectorParams,
pub worldline: ConnectorParams,
pub worldpay: ConnectorParams,
+ pub xendit: ConnectorParams,
pub zen: ConnectorParams,
pub zsl: ConnectorParams,
}
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 7913d6543c8..e98730d006d 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -57,7 +57,7 @@ pub use hyperswitch_connectors::connectors::{
powertranz::Powertranz, razorpay, razorpay::Razorpay, shift4, shift4::Shift4, square,
square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys,
tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline, worldpay, worldpay::Worldpay,
- zen, zen::Zen, zsl, zsl::Zsl,
+ xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl,
};
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index b432c57c5d1..f7909a97195 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -496,6 +496,9 @@ impl ConnectorData {
enums::Connector::Worldpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new())))
}
+ // enums::Connector::Xendit => {
+ // Ok(ConnectorEnum::Old(Box::new(connector::Xendit::new())))
+ // }
enums::Connector::Mifinity => {
Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new())))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index c97084a2297..6d11dbfeb2e 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -303,6 +303,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Wise => Self::Wise,
api_enums::Connector::Worldline => Self::Worldline,
api_enums::Connector::Worldpay => Self::Worldpay,
+ // api_enums::Connector::Xendit => Self::Xendit,
api_enums::Connector::Zen => Self::Zen,
api_enums::Connector::Zsl => Self::Zsl,
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/tests/connectors/xendit.rs b/crates/router/tests/connectors/xendit.rs
new file mode 100644
index 00000000000..452f22a1122
--- /dev/null
+++ b/crates/router/tests/connectors/xendit.rs
@@ -0,0 +1,402 @@
+use masking::Secret;
+use router::{
+ types::{self, api, storage::enums,
+}};
+
+use crate::utils::{self, ConnectorActions};
+use test_utils::connector_auth;
+
+#[derive(Clone, Copy)]
+struct XenditTest;
+impl ConnectorActions for XenditTest {}
+impl utils::Connector for XenditTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Xendit;
+ api::ConnectorData {
+ connector: Box::new(Xendit::new()),
+ connector_name: types::Connector::Xendit,
+ get_token: types::api::GetToken::Connector,
+ merchant_connector_id: None,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .xendit
+ .expect("Missing connector authentication configuration").into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "xendit".to_string()
+ }
+}
+
+static CONNECTOR: XenditTest = XenditTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: api::PaymentMethodData::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: api::PaymentMethodData::Card(api::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index be02e5720fb..2b2dc143113 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -92,6 +92,7 @@ pub struct ConnectorAuthentication {
// pub wellsfargopayout: Option<HeaderKey>,
pub wise: Option<BodyKey>,
pub worldpay: Option<BodyKey>,
+ pub xendit: Option<HeaderKey>,
pub worldline: Option<SignatureKey>,
pub zen: Option<HeaderKey>,
pub zsl: Option<BodyKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 934b072f14a..a7ea6e43e86 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -166,6 +166,7 @@ wellsfargo.base_url = "https://apitest.cybersource.com/"
wellsfargopayout.base_url = "https://api-sandbox.wellsfargo.com/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
worldpay.base_url = "https://try.access.worldpay.com/"
+xendit.base_url = "https://api.xendit.co"
wise.base_url = "https://api.sandbox.transferwise.tech/"
zen.base_url = "https://api.zen-test.com/"
zen.secondary_base_url = "https://secure.zen-test.com/"
@@ -253,6 +254,7 @@ cards = [
"wise",
"worldline",
"worldpay",
+ "xendit",
"zen",
"zsl",
]
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 0ed38e8ef5d..9f1992bfa44 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res="$(echo ${sorted[@]})"
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-11-18T10:24:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Template code added for new connector Xendit
https://developers.xendit.co/api-reference
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/6597
## How did you test it?
Since this is template PR, no testing is required.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d32397f060731f51a15634e221117a554b8b3721
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6572
|
Bug: feat(analytics): add `sessionized_metrics` for disputes (backwards compatibility)
## Current Behaviour
- There is no `sessionized_metrics` module for disputes like there is for `payments` and `payment_intents`
## Proposed Changes
- create `sessionized_metrics` module for disputes
|
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 546b57f99af..f56e875f720 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -139,6 +139,9 @@ impl AnalyticsDataSource for ClickhouseClient {
| AnalyticsCollection::Dispute => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
}
+ AnalyticsCollection::DisputeSessionized => {
+ TableEngine::CollapsingMergeTree { sign: "sign_flag" }
+ }
AnalyticsCollection::SdkEvents
| AnalyticsCollection::SdkEventsAnalytics
| AnalyticsCollection::ApiEvents
@@ -439,6 +442,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection {
Self::ConnectorEvents => Ok("connector_events_audit".to_string()),
Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()),
Self::Dispute => Ok("dispute".to_string()),
+ Self::DisputeSessionized => Ok("sessionizer_dispute".to_string()),
Self::ActivePaymentsAnalytics => Ok("active_payments".to_string()),
}
}
diff --git a/crates/analytics/src/disputes/accumulators.rs b/crates/analytics/src/disputes/accumulators.rs
index 1997d75d323..41bd3beebdb 100644
--- a/crates/analytics/src/disputes/accumulators.rs
+++ b/crates/analytics/src/disputes/accumulators.rs
@@ -5,8 +5,8 @@ use super::metrics::DisputeMetricRow;
#[derive(Debug, Default)]
pub struct DisputeMetricsAccumulator {
pub disputes_status_rate: RateAccumulator,
- pub total_amount_disputed: SumAccumulator,
- pub total_dispute_lost_amount: SumAccumulator,
+ pub disputed_amount: DisputedAmountAccumulator,
+ pub dispute_lost_amount: DisputedAmountAccumulator,
}
#[derive(Debug, Default)]
pub struct RateAccumulator {
@@ -17,7 +17,7 @@ pub struct RateAccumulator {
}
#[derive(Debug, Default)]
#[repr(transparent)]
-pub struct SumAccumulator {
+pub struct DisputedAmountAccumulator {
pub total: Option<i64>,
}
@@ -29,7 +29,7 @@ pub trait DisputeMetricAccumulator {
fn collect(self) -> Self::MetricOutput;
}
-impl DisputeMetricAccumulator for SumAccumulator {
+impl DisputeMetricAccumulator for DisputedAmountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
@@ -92,8 +92,8 @@ impl DisputeMetricsAccumulator {
disputes_challenged: challenge_rate,
disputes_won: won_rate,
disputes_lost: lost_rate,
- total_amount_disputed: self.total_amount_disputed.collect(),
- total_dispute_lost_amount: self.total_dispute_lost_amount.collect(),
+ disputed_amount: self.disputed_amount.collect(),
+ dispute_lost_amount: self.dispute_lost_amount.collect(),
total_dispute,
}
}
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs
index b8b44a757de..85d1a62a1d9 100644
--- a/crates/analytics/src/disputes/core.rs
+++ b/crates/analytics/src/disputes/core.rs
@@ -5,8 +5,8 @@ use api_models::analytics::{
DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier,
DisputeMetricsBucketResponse,
},
- AnalyticsMetadata, DisputeFilterValue, DisputeFiltersResponse, GetDisputeFilterRequest,
- GetDisputeMetricRequest, MetricsResponse,
+ DisputeFilterValue, DisputeFiltersResponse, DisputesAnalyticsMetadata, DisputesMetricsResponse,
+ GetDisputeFilterRequest, GetDisputeMetricRequest,
};
use error_stack::ResultExt;
use router_env::{
@@ -30,7 +30,7 @@ pub async fn get_metrics(
pool: &AnalyticsProvider,
auth: &AuthInfo,
req: GetDisputeMetricRequest,
-) -> AnalyticsResult<MetricsResponse<DisputeMetricsBucketResponse>> {
+) -> AnalyticsResult<DisputesMetricsResponse<DisputeMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
DisputeMetricsBucketIdentifier,
DisputeMetricsAccumulator,
@@ -87,14 +87,17 @@ 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 {
- DisputeMetrics::DisputeStatusMetric => metrics_builder
+ DisputeMetrics::DisputeStatusMetric
+ | DisputeMetrics::SessionizedDisputeStatusMetric => metrics_builder
.disputes_status_rate
.add_metrics_bucket(&value),
- DisputeMetrics::TotalAmountDisputed => metrics_builder
- .total_amount_disputed
- .add_metrics_bucket(&value),
- DisputeMetrics::TotalDisputeLostAmount => metrics_builder
- .total_dispute_lost_amount
+ DisputeMetrics::TotalAmountDisputed
+ | DisputeMetrics::SessionizedTotalAmountDisputed => {
+ metrics_builder.disputed_amount.add_metrics_bucket(&value)
+ }
+ DisputeMetrics::TotalDisputeLostAmount
+ | DisputeMetrics::SessionizedTotalDisputeLostAmount => metrics_builder
+ .dispute_lost_amount
.add_metrics_bucket(&value),
}
}
@@ -105,18 +108,31 @@ pub async fn get_metrics(
metrics_accumulator
);
}
+ let mut total_disputed_amount = 0;
+ let mut total_dispute_lost_amount = 0;
let query_data: Vec<DisputeMetricsBucketResponse> = metrics_accumulator
.into_iter()
- .map(|(id, val)| DisputeMetricsBucketResponse {
- values: val.collect(),
- dimensions: id,
+ .map(|(id, val)| {
+ let collected_values = val.collect();
+ if let Some(amount) = collected_values.disputed_amount {
+ total_disputed_amount += amount;
+ }
+ if let Some(amount) = collected_values.dispute_lost_amount {
+ total_dispute_lost_amount += amount;
+ }
+
+ DisputeMetricsBucketResponse {
+ values: collected_values,
+ dimensions: id,
+ }
})
.collect();
- Ok(MetricsResponse {
+ Ok(DisputesMetricsResponse {
query_data,
- meta_data: [AnalyticsMetadata {
- current_time_range: req.time_range,
+ meta_data: [DisputesAnalyticsMetadata {
+ total_disputed_amount: Some(total_disputed_amount),
+ total_dispute_lost_amount: Some(total_dispute_lost_amount),
}],
})
}
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
index dd1aa3c1bbd..ad7ed81aaee 100644
--- a/crates/analytics/src/disputes/metrics.rs
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -1,4 +1,5 @@
mod dispute_status_metric;
+mod sessionized_metrics;
mod total_amount_disputed;
mod total_dispute_lost_amount;
@@ -92,6 +93,21 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::SessionizedTotalAmountDisputed => {
+ sessionized_metrics::TotalAmountDisputed::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedDisputeStatusMetric => {
+ sessionized_metrics::DisputeStatusMetric::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedTotalDisputeLostAmount => {
+ sessionized_metrics::TotalDisputeLostAmount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs
new file mode 100644
index 00000000000..c5c0b91a173
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs
@@ -0,0 +1,120 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct DisputeStatusMetric {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for DisputeStatusMetric
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ auth: &AuthInfo,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
+
+ for dim in dimensions {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder.add_select_column("dispute_status").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).switch()?;
+
+ for dim in dimensions {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("dispute_status")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.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<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs
new file mode 100644
index 00000000000..4d41194634d
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs
@@ -0,0 +1,8 @@
+mod dispute_status_metric;
+mod total_amount_disputed;
+mod total_dispute_lost_amount;
+pub(super) use dispute_status_metric::DisputeStatusMetric;
+pub(super) use total_amount_disputed::TotalAmountDisputed;
+pub(super) use total_dispute_lost_amount::TotalDisputeLostAmount;
+
+pub use super::{DisputeMetric, DisputeMetricAnalytics, DisputeMetricRow};
diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs
new file mode 100644
index 00000000000..0767bdaf85d
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs
@@ -0,0 +1,118 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct TotalAmountDisputed {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for TotalAmountDisputed
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ auth: &AuthInfo,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
+
+ for dim in dimensions {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "dispute_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).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+ query_builder
+ .add_filter_clause("dispute_status", "dispute_won")
+ .switch()?;
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.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/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs
new file mode 100644
index 00000000000..f4f4d860862
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs
@@ -0,0 +1,119 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct TotalDisputeLostAmount {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ auth: &AuthInfo,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "dispute_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).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause("dispute_status", "dispute_lost")
+ .switch()?;
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.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/sqlx.rs b/crates/analytics/src/sqlx.rs
index 0a641fbc5f9..80fcaf8ad4e 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -927,6 +927,8 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
Self::OutgoingWebhookEvent => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("OutgoingWebhookEvents table is not implemented for Sqlx"))?,
Self::Dispute => Ok("dispute".to_string()),
+ Self::DisputeSessionized => Err(error_stack::report!(ParsingError::UnknownError)
+ .attach_printable("DisputeSessionized table is not implemented for Sqlx"))?,
}
}
}
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 6bdd11fcd73..86056338106 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -38,6 +38,7 @@ pub enum AnalyticsCollection {
ConnectorEvents,
OutgoingWebhookEvent,
Dispute,
+ DisputeSessionized,
ApiEventsAnalytics,
ActivePaymentsAnalytics,
}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 70c0e0e78dc..ee904652154 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -346,6 +346,11 @@ pub struct SdkEventFilterValue {
pub values: Vec<String>,
}
+#[derive(Debug, serde::Serialize)]
+pub struct DisputesAnalyticsMetadata {
+ pub total_disputed_amount: Option<u64>,
+ pub total_dispute_lost_amount: Option<u64>,
+}
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetricsResponse<T> {
@@ -373,6 +378,12 @@ pub struct RefundsMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [RefundsAnalyticsMetadata; 1],
}
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DisputesMetricsResponse<T> {
+ pub query_data: Vec<T>,
+ pub meta_data: [DisputesAnalyticsMetadata; 1],
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs
index edb85c129e6..2509d83e132 100644
--- a/crates/api_models/src/analytics/disputes.rs
+++ b/crates/api_models/src/analytics/disputes.rs
@@ -24,6 +24,9 @@ pub enum DisputeMetrics {
DisputeStatusMetric,
TotalAmountDisputed,
TotalDisputeLostAmount,
+ SessionizedDisputeStatusMetric,
+ SessionizedTotalAmountDisputed,
+ SessionizedTotalDisputeLostAmount,
}
#[derive(
@@ -122,8 +125,8 @@ pub struct DisputeMetricsBucketValue {
pub disputes_challenged: Option<u64>,
pub disputes_won: Option<u64>,
pub disputes_lost: Option<u64>,
- pub total_amount_disputed: Option<u64>,
- pub total_dispute_lost_amount: Option<u64>,
+ pub disputed_amount: Option<u64>,
+ pub dispute_lost_amount: Option<u64>,
pub total_dispute: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 77d8cb117ef..541c59e1adc 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -173,6 +173,12 @@ impl<T> ApiEventMetric for RefundsMetricsResponse<T> {
Some(ApiEventsType::Miscellaneous)
}
}
+
+impl<T> ApiEventMetric for DisputesMetricsResponse<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> {
|
2024-11-14T12:49:06Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Add sessionized metrics module and implement backwards compatibility.
- Add the `sessionizer_dispute` table support for Sessionized metrics.
### Fixes #6572
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Dispute metrics didn't have a `sessionized_metrics` module and implementation as were there in payments and payment_intents metrics
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \
--header 'Accept: */*' \
--header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStat' \
--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/130.0.0.0 Safari/537.36' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-11-06T18:30:00Z",
"endTime": "2024-11-14T10:51:00Z"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"dispute_status_metric",
"total_amount_disputed",
"total_dispute_lost_amount"
],
"delta": true
}
]'
```
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \
--header 'Accept: */*' \
--header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStat' \
--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/130.0.0.0 Safari/537.36' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTY1MTcyMCwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.gtctUL339INfdj6CVmZLW2NDMNcseMTCPX0uxSsOD1c' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-11-06T18:30:00Z",
"endTime": "2024-11-14T10:51:00Z"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_dispute_status_metric",
"sessionized_total_amount_disputed",
"sessionized_total_dispute_lost_amount"
],
"delta": true
}
]'
```
<img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3">
<img width="1289" alt="Screenshot 2024-11-14 at 6 14 32 PM" src="https://github.com/user-attachments/assets/ce8b0aeb-6f4f-4242-a329-4183a97ea8b3">
### Result: Earlier it used to throw `5xx` for sessionized metrics but here it's giving us `200` for both metrics.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8cc5d3db9afb120b00115c6714be2e362951cc94
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6565
|
Bug: Elimination routing integration
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index c4c2f072b1e..2e570816ab4 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -740,14 +740,13 @@ pub struct ToggleDynamicRoutingPath {
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct EliminationRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
- // pub labels: Option<Vec<String>>,
pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct EliminationAnalyserConfig {
- pub bucket_size: Option<u32>,
- pub bucket_ttl_in_mins: Option<f64>,
+ pub bucket_size: Option<u64>,
+ pub bucket_leak_interval_in_secs: Option<u64>,
}
impl Default for EliminationRoutingConfig {
@@ -756,7 +755,7 @@ impl Default for EliminationRoutingConfig {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
elimination_analyser_config: Some(EliminationAnalyserConfig {
bucket_size: Some(5),
- bucket_ttl_in_mins: Some(2.0),
+ bucket_leak_interval_in_secs: Some(2),
}),
}
}
@@ -860,3 +859,18 @@ impl CurrentBlockThreshold {
}
}
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
+pub struct RoutableConnectorChoiceWithBucketName {
+ pub routable_connector_choice: RoutableConnectorChoice,
+ pub bucket_name: String,
+}
+
+impl RoutableConnectorChoiceWithBucketName {
+ pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self {
+ Self {
+ routable_connector_choice,
+ bucket_name,
+ }
+ }
+}
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
index 0a4938e94b4..b3fa1a8fed2 100644
--- a/crates/external_services/build.rs
+++ b/crates/external_services/build.rs
@@ -6,7 +6,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let proto_path = router_env::workspace_path().join("proto");
let success_rate_proto_file = proto_path.join("success_rate.proto");
-
+ let elimination_proto_file = proto_path.join("elimination_rate.proto");
let health_check_proto_file = proto_path.join("health_check.proto");
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
@@ -14,7 +14,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.out_dir(out_dir)
.compile(
- &[success_rate_proto_file, health_check_proto_file],
+ &[
+ success_rate_proto_file,
+ elimination_proto_file,
+ health_check_proto_file,
+ ],
&[proto_path],
)
.expect("Failed to compile proto files");
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index 7ec42de0d7c..e5050227fa8 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -1,31 +1,17 @@
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 common_utils::errors::CustomResult;
use router_env::logger;
use serde;
-use success_rate::{
- success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
- CalSuccessRateRequest, CalSuccessRateResponse,
- CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
- InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig,
- UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
-};
+/// Elimination Routing Client Interface Implementation
+pub mod elimination_rate_client;
+/// Success Routing Client Interface Implementation
+pub mod success_rate_client;
+
+pub use elimination_rate_client::EliminationAnalyserClient;
+pub use success_rate_client::SuccessRateCalculatorClient;
use super::Client;
-#[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>;
@@ -38,9 +24,12 @@ pub enum DynamicRoutingError {
/// The required field name
field: String,
},
- /// Error from Dynamic Routing Server
- #[error("Error from Dynamic Routing Server : {0}")]
+ /// Error from Dynamic Routing Server while performing success_rate analysis
+ #[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")]
SuccessRateBasedRoutingFailure(String),
+ /// Error from Dynamic Routing Server while perfrming elimination
+ #[error("Error from Dynamic Routing Server while perfrming elimination : {0}")]
+ EliminationRateRoutingFailure(String),
}
/// Type that consists of all the services provided by the client
@@ -48,6 +37,8 @@ pub enum DynamicRoutingError {
pub struct RoutingStrategy {
/// success rate service for Dynamic Routing
pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>,
+ /// elimination service for Dynamic Routing
+ pub elimination_rate_client: Option<EliminationAnalyserClient<Client>>,
}
/// Contains the Dynamic Routing Client Config
@@ -74,190 +65,23 @@ impl DynamicRoutingClientConfig {
self,
client: Client,
) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
- let success_rate_client = match self {
+ let (success_rate_client, elimination_rate_client) = match self {
Self::Enabled { host, port, .. } => {
let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?;
logger::info!("Connection established with dynamic routing gRPC Server");
- Some(SuccessRateCalculatorClient::with_origin(client, uri))
+ (
+ Some(SuccessRateCalculatorClient::with_origin(
+ client.clone(),
+ uri.clone(),
+ )),
+ Some(EliminationAnalyserClient::with_origin(client, uri)),
+ )
}
- Self::Disabled => None,
+ Self::Disabled => (None, 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,
- params: String,
- 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,
- 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]
-impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
- async fn calculate_success_rate(
- &self,
- id: String,
- success_rate_based_config: SuccessBasedRoutingConfig,
- params: String,
- label_input: Vec<RoutableConnectorChoice>,
- ) -> DynamicRoutingResult<CalSuccessRateResponse> {
- 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 response = self
- .clone()
- .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,
- params: String,
- 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 request = tonic::Request::new(UpdateSuccessRateWindowRequest {
- id,
- params,
- labels_with_status,
- config,
- });
-
- let response = self
- .clone()
- .update_success_rate_window(request)
- .await
- .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
- "Failed to update the success rate window".to_string(),
- ))?
- .into_inner();
-
- 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 {
- 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(),
- })?,
+ elimination_rate_client,
})
}
}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs
new file mode 100644
index 00000000000..6587b7941f4
--- /dev/null
+++ b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs
@@ -0,0 +1,158 @@
+use api_models::routing::{
+ EliminationAnalyserConfig as EliminationConfig, RoutableConnectorChoice,
+ RoutableConnectorChoiceWithBucketName,
+};
+use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
+pub use elimination_rate::{
+ elimination_analyser_client::EliminationAnalyserClient, EliminationBucketConfig,
+ EliminationRequest, EliminationResponse, InvalidateBucketRequest, InvalidateBucketResponse,
+ LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse,
+};
+use error_stack::ResultExt;
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions,
+ clippy::use_self
+)]
+pub mod elimination_rate {
+ tonic::include_proto!("elimination");
+}
+
+use super::{Client, DynamicRoutingError, DynamicRoutingResult};
+
+/// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket
+#[async_trait::async_trait]
+pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync {
+ /// To perform the elimination based routing for the list of connectors
+ async fn perform_elimination_routing(
+ &self,
+ id: String,
+ params: String,
+ labels: Vec<RoutableConnectorChoice>,
+ configs: Option<EliminationConfig>,
+ ) -> DynamicRoutingResult<EliminationResponse>;
+ /// To update the bucket size and ttl for list of connectors with its respective bucket name
+ async fn update_elimination_bucket_config(
+ &self,
+ id: String,
+ params: String,
+ report: Vec<RoutableConnectorChoiceWithBucketName>,
+ config: Option<EliminationConfig>,
+ ) -> DynamicRoutingResult<UpdateEliminationBucketResponse>;
+ /// To invalidate the previous id's bucket
+ async fn invalidate_elimination_bucket(
+ &self,
+ id: String,
+ ) -> DynamicRoutingResult<InvalidateBucketResponse>;
+}
+
+#[async_trait::async_trait]
+impl EliminationBasedRouting for EliminationAnalyserClient<Client> {
+ async fn perform_elimination_routing(
+ &self,
+ id: String,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ configs: Option<EliminationConfig>,
+ ) -> DynamicRoutingResult<EliminationResponse> {
+ let labels = label_input
+ .into_iter()
+ .map(|conn_choice| conn_choice.to_string())
+ .collect::<Vec<_>>();
+
+ let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
+
+ let request = tonic::Request::new(EliminationRequest {
+ id,
+ params,
+ labels,
+ config,
+ });
+
+ let response = self
+ .clone()
+ .get_elimination_status(request)
+ .await
+ .change_context(DynamicRoutingError::EliminationRateRoutingFailure(
+ "Failed to perform the elimination analysis".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+
+ async fn update_elimination_bucket_config(
+ &self,
+ id: String,
+ params: String,
+ report: Vec<RoutableConnectorChoiceWithBucketName>,
+ configs: Option<EliminationConfig>,
+ ) -> DynamicRoutingResult<UpdateEliminationBucketResponse> {
+ let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
+
+ let labels_with_bucket_name = report
+ .into_iter()
+ .map(|conn_choice_with_bucket| LabelWithBucketName {
+ label: conn_choice_with_bucket
+ .routable_connector_choice
+ .to_string(),
+ bucket_name: conn_choice_with_bucket.bucket_name,
+ })
+ .collect::<Vec<_>>();
+
+ let request = tonic::Request::new(UpdateEliminationBucketRequest {
+ id,
+ params,
+ labels_with_bucket_name,
+ config,
+ });
+
+ let response = self
+ .clone()
+ .update_elimination_bucket(request)
+ .await
+ .change_context(DynamicRoutingError::EliminationRateRoutingFailure(
+ "Failed to update the elimination bucket".to_string(),
+ ))?
+ .into_inner();
+ Ok(response)
+ }
+ async fn invalidate_elimination_bucket(
+ &self,
+ id: String,
+ ) -> DynamicRoutingResult<InvalidateBucketResponse> {
+ let request = tonic::Request::new(InvalidateBucketRequest { id });
+
+ let response = self
+ .clone()
+ .invalidate_bucket(request)
+ .await
+ .change_context(DynamicRoutingError::EliminationRateRoutingFailure(
+ "Failed to invalidate the elimination bucket".to_string(),
+ ))?
+ .into_inner();
+ Ok(response)
+ }
+}
+
+impl ForeignTryFrom<EliminationConfig> for EliminationBucketConfig {
+ type Error = error_stack::Report<DynamicRoutingError>;
+ fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> {
+ Ok(Self {
+ bucket_size: config
+ .bucket_size
+ .get_required_value("bucket_size")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "bucket_size".to_string(),
+ })?,
+ bucket_leak_interval_in_secs: config
+ .bucket_leak_interval_in_secs
+ .get_required_value("bucket_leak_interval_in_secs")
+ .change_context(DynamicRoutingError::MissingRequiredField {
+ field: "bucket_leak_interval_in_secs".to_string(),
+ })?,
+ })
+ }
+}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
new file mode 100644
index 00000000000..f6d3efb8876
--- /dev/null
+++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs
@@ -0,0 +1,195 @@
+use api_models::routing::{
+ CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,
+};
+use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom};
+use error_stack::ResultExt;
+pub use success_rate::{
+ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
+ CalSuccessRateRequest, CalSuccessRateResponse,
+ CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest,
+ InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig,
+ UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
+};
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions
+)]
+pub mod success_rate {
+ tonic::include_proto!("success_rate");
+}
+use super::{Client, DynamicRoutingError, DynamicRoutingResult};
+/// 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,
+ params: String,
+ 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,
+ 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]
+impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
+ async fn calculate_success_rate(
+ &self,
+ id: String,
+ success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
+ label_input: Vec<RoutableConnectorChoice>,
+ ) -> DynamicRoutingResult<CalSuccessRateResponse> {
+ 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 response = self
+ .clone()
+ .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,
+ params: String,
+ 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 request = tonic::Request::new(UpdateSuccessRateWindowRequest {
+ id,
+ params,
+ labels_with_status,
+ config,
+ });
+
+ let response = self
+ .clone()
+ .update_success_rate_window(request)
+ .await
+ .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
+ "Failed to update the success rate window".to_string(),
+ ))?
+ .into_inner();
+
+ 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 {
+ 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/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index b3be47a8743..746b6b7fb40 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -23,8 +23,8 @@ use euclid::{
frontend::{ast, dir as euclid_dir},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use external_services::grpc_client::dynamic_routing::{
- success_rate::CalSuccessRateResponse, SuccessBasedDynamicRouting,
+use external_services::grpc_client::dynamic_routing::success_rate_client::{
+ CalSuccessRateResponse, SuccessBasedDynamicRouting,
};
use hyperswitch_domain_models::address::Address;
use kgraph_utils::{
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index cdd8b518f35..22301d4314f 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -12,7 +12,7 @@ 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 external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting;
use hyperswitch_domain_models::{mandates, payment_address};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use router_env::logger;
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 6a5e3bd0264..89fc29cf1b2 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -16,7 +16,7 @@ use diesel_models::configs;
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
-use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting;
+use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
diff --git a/proto/elimination_rate.proto b/proto/elimination_rate.proto
new file mode 100644
index 00000000000..c5f10597ade
--- /dev/null
+++ b/proto/elimination_rate.proto
@@ -0,0 +1,67 @@
+syntax = "proto3";
+package elimination;
+
+service EliminationAnalyser {
+ rpc GetEliminationStatus (EliminationRequest) returns (EliminationResponse);
+
+ rpc UpdateEliminationBucket (UpdateEliminationBucketRequest) returns (UpdateEliminationBucketResponse);
+
+ rpc InvalidateBucket (InvalidateBucketRequest) returns (InvalidateBucketResponse);
+}
+
+// API-1 types
+message EliminationRequest {
+ string id = 1;
+ string params = 2;
+ repeated string labels = 3;
+ EliminationBucketConfig config = 4;
+}
+
+message EliminationBucketConfig {
+ uint64 bucket_size = 1;
+ uint64 bucket_leak_interval_in_secs = 2;
+}
+
+message EliminationResponse {
+ repeated LabelWithStatus labels_with_status = 1;
+}
+
+message LabelWithStatus {
+ string label = 1;
+ bool is_eliminated = 2;
+ string bucket_name = 3;
+}
+
+// API-2 types
+message UpdateEliminationBucketRequest {
+ string id = 1;
+ string params = 2;
+ repeated LabelWithBucketName labels_with_bucket_name = 3;
+ EliminationBucketConfig config = 4;
+}
+
+message LabelWithBucketName {
+ string label = 1;
+ string bucket_name = 2;
+}
+
+message UpdateEliminationBucketResponse {
+ enum UpdationStatus {
+ BUCKET_UPDATION_SUCCEEDED = 0;
+ BUCKET_UPDATION_FAILED = 1;
+ }
+ UpdationStatus status = 1;
+}
+
+// API-3 types
+message InvalidateBucketRequest {
+ string id = 1;
+}
+
+message InvalidateBucketResponse {
+ enum InvalidationStatus {
+ BUCKET_INVALIDATION_SUCCEEDED = 0;
+ BUCKET_INVALIDATION_FAILED = 1;
+ }
+ InvalidationStatus status = 1;
+}
\ No newline at end of file
|
2024-11-27T07:23:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
build the gRPC interface for communicating with the external service to perform elimination 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?
- Communication is being established with dynamo
<img width="1705" alt="Screenshot 2024-12-05 at 6 03 54 PM" src="https://github.com/user-attachments/assets/09c62052-6c86-47a2-b03f-da0c2835df55">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d75625f11d4611c688593d5730efc8c6f2c59afd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6564
|
Bug: Volume Split for Intelligent Routing
Hyperswitch currently supports both static and dynamic routing. Develop a feature to provide a volume split between these routing types itself. Example - 20% of the payments, make decisions based on dynamic routing and 80% of the payments, based on static routing.
|
diff --git a/config/development.toml b/config/development.toml
index eef44648c6c..4e3a9b09993 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -790,9 +790,10 @@ card_networks = "Visa, AmericanExpress, Mastercard"
[network_tokenization_supported_connectors]
connector_list = "cybersource"
-[grpc_client.dynamic_routing_client]
-host = "localhost"
-port = 7000
+[grpc_client.dynamic_routing_client]
+host = "localhost"
+port = 7000
+service = "dynamo"
[theme_storage]
file_storage_backend = "file_system"
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index 87e7fa27885..f3e169336bf 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -4,9 +4,9 @@ use crate::routing::{
LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig,
RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind,
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
- RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, SuccessBasedRoutingConfig,
- SuccessBasedRoutingPayloadWrapper, SuccessBasedRoutingUpdateConfigQuery,
- ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper,
+ RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper,
+ SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper,
+ SuccessBasedRoutingUpdateConfigQuery, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
@@ -108,3 +108,9 @@ impl ApiEventMetric for SuccessBasedRoutingUpdateConfigQuery {
Some(ApiEventsType::Routing)
}
}
+
+impl ApiEventMetric for RoutingVolumeSplitWrapper {
+ 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 6cd5d5251a3..c4c2f072b1e 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -522,6 +522,7 @@ pub struct DynamicAlgorithmWithTimestamp<T> {
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
+ pub dynamic_routing_volume_split: Option<u8>,
pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
}
@@ -554,32 +555,6 @@ impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
}
}
-impl EliminationRoutingAlgorithm {
- pub fn new(
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
- common_utils::id_type::RoutingId,
- >,
- ) -> Self {
- Self {
- algorithm_id_with_timestamp,
- enabled_feature: DynamicRoutingFeatures::None,
- }
- }
-}
-
-impl SuccessBasedAlgorithm {
- pub fn new(
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
- common_utils::id_type::RoutingId,
- >,
- ) -> Self {
- Self {
- algorithm_id_with_timestamp,
- enabled_feature: DynamicRoutingFeatures::None,
- }
- }
-}
-
impl DynamicRoutingAlgorithmRef {
pub fn update(&mut self, new: Self) {
if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
@@ -608,8 +583,63 @@ impl DynamicRoutingAlgorithmRef {
}
}
}
+
+ pub fn update_volume_split(&mut self, volume: Option<u8>) {
+ self.dynamic_routing_volume_split = volume
+ }
+}
+
+impl EliminationRoutingAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
+impl SuccessBasedAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
+#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
+pub struct RoutingVolumeSplit {
+ pub routing_type: RoutingType,
+ pub split: u8,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct RoutingVolumeSplitWrapper {
+ pub routing_info: RoutingVolumeSplit,
+ pub profile_id: common_utils::id_type::ProfileId,
+}
+
+#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum RoutingType {
+ #[default]
+ Static,
+ Dynamic,
+}
+
+impl RoutingType {
+ pub fn is_dynamic_routing(self) -> bool {
+ self == Self::Dynamic
+ }
+}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedAlgorithm {
pub algorithm_id_with_timestamp:
@@ -673,6 +703,11 @@ pub struct ToggleDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
}
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct DynamicRoutingVolumeSplitQuery {
+ pub split: u8,
+}
+
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum DynamicRoutingFeatures {
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 9b02c67ce6a..666b648523d 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -211,3 +211,6 @@ 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";
+
+/// Max volume split for Dynamic routing
+pub const DYNAMIC_ROUTING_MAX_VOLUME: u8 = 100;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index fd9eaaa9c77..1dd9400b8bc 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -6026,47 +6026,75 @@ where
// dynamic success based connector selection
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
let connectors = {
- if business_profile.dynamic_routing_algorithm.is_some() {
- let success_based_routing_config_params_interpolator =
- routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
- payment_data.get_payment_attempt().payment_method,
- payment_data.get_payment_attempt().payment_method_type,
- payment_data.get_payment_attempt().authentication_type,
- payment_data.get_payment_attempt().currency,
- payment_data
- .get_billing_address()
- .and_then(|address| address.address)
- .and_then(|address| address.country),
- payment_data
- .get_payment_attempt()
- .payment_method_data
- .as_ref()
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card"))
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card_network"))
- .and_then(|network| network.as_str())
- .map(|network| network.to_string()),
- payment_data
- .get_payment_attempt()
- .payment_method_data
- .as_ref()
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card"))
- .and_then(|data| data.as_object())
- .and_then(|card| card.get("card_isin"))
- .and_then(|card_isin| card_isin.as_str())
- .map(|card_isin| card_isin.to_string()),
- );
- routing::perform_success_based_routing(
- state,
- connectors.clone(),
- business_profile,
- success_based_routing_config_params_interpolator,
- )
- .await
- .map_err(|e| logger::error!(success_rate_routing_error=?e))
- .unwrap_or(connectors)
+ if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() {
+ let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo
+ .parse_value("DynamicRoutingAlgorithmRef")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?;
+ let dynamic_split = api_models::routing::RoutingVolumeSplit {
+ routing_type: api_models::routing::RoutingType::Dynamic,
+ split: dynamic_routing_config
+ .dynamic_routing_volume_split
+ .unwrap_or_default(),
+ };
+ let static_split: api_models::routing::RoutingVolumeSplit =
+ api_models::routing::RoutingVolumeSplit {
+ routing_type: api_models::routing::RoutingType::Static,
+ split: crate::consts::DYNAMIC_ROUTING_MAX_VOLUME
+ - dynamic_routing_config
+ .dynamic_routing_volume_split
+ .unwrap_or_default(),
+ };
+ let volume_split_vec = vec![dynamic_split, static_split];
+ let routing_choice =
+ routing::perform_dynamic_routing_volume_split(volume_split_vec, None)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to perform volume split on routing type")?;
+
+ if routing_choice.routing_type.is_dynamic_routing() {
+ let success_based_routing_config_params_interpolator =
+ routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
+ payment_data.get_payment_attempt().payment_method,
+ payment_data.get_payment_attempt().payment_method_type,
+ payment_data.get_payment_attempt().authentication_type,
+ payment_data.get_payment_attempt().currency,
+ payment_data
+ .get_billing_address()
+ .and_then(|address| address.address)
+ .and_then(|address| address.country),
+ payment_data
+ .get_payment_attempt()
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
+ payment_data
+ .get_payment_attempt()
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_isin"))
+ .and_then(|card_isin| card_isin.as_str())
+ .map(|card_isin| card_isin.to_string()),
+ );
+ routing::perform_success_based_routing(
+ state,
+ connectors.clone(),
+ business_profile,
+ success_based_routing_config_params_interpolator,
+ )
+ .await
+ .map_err(|e| logger::error!(success_rate_routing_error=?e))
+ .unwrap_or(connectors)
+ } else {
+ connectors
+ }
} else {
connectors
}
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 76456c8dbc9..b3be47a8743 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -489,6 +489,36 @@ pub async fn refresh_routing_cache_v1(
Ok(arc_cached_algorithm)
}
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub fn perform_dynamic_routing_volume_split(
+ splits: Vec<api_models::routing::RoutingVolumeSplit>,
+ rng_seed: Option<&str>,
+) -> RoutingResult<api_models::routing::RoutingVolumeSplit> {
+ let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
+ let weighted_index = distributions::WeightedIndex::new(weights)
+ .change_context(errors::RoutingError::VolumeSplitFailed)
+ .attach_printable("Error creating weighted distribution for volume split")?;
+
+ let idx = if let Some(seed) = rng_seed {
+ let mut hasher = hash_map::DefaultHasher::new();
+ seed.hash(&mut hasher);
+ let hash = hasher.finish();
+
+ let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash);
+ weighted_index.sample(&mut rng)
+ } else {
+ let mut rng = rand::thread_rng();
+ weighted_index.sample(&mut rng)
+ };
+
+ let routing_choice = *splits
+ .get(idx)
+ .ok_or(errors::RoutingError::VolumeSplitFailed)
+ .attach_printable("Volume split index lookup failed")?;
+
+ Ok(routing_choice)
+}
+
pub fn perform_volume_split(
mut splits: Vec<routing_types::ConnectorVolumeSplit>,
rng_seed: Option<&str>,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 9318e0c5b9f..f7a89396397 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -15,7 +15,9 @@ use error_stack::ResultExt;
use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting;
use hyperswitch_domain_models::{mandates, payment_address};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use router_env::{logger, metrics::add_attributes};
+use router_env::logger;
+#[cfg(feature = "v1")]
+use router_env::metrics::add_attributes;
use rustc_hash::FxHashSet;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use storage_impl::redis::cache;
@@ -1271,6 +1273,69 @@ pub async fn toggle_specific_dynamic_routing(
}
}
+#[cfg(feature = "v1")]
+pub async fn configure_dynamic_routing_volume_split(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ profile_id: common_utils::id_type::ProfileId,
+ routing_info: routing::RoutingVolumeSplit,
+) -> RouterResponse<()> {
+ 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();
+
+ utils::when(
+ routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME,
+ || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Dynamic routing volume split should be less than 100".to_string(),
+ })
+ },
+ )?;
+
+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ &key_store,
+ Some(&profile_id),
+ merchant_account.get_id(),
+ )
+ .await?
+ .get_required_value("Profile")
+ .change_context(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id.get_string_repr().to_owned(),
+ })?;
+
+ let mut 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();
+
+ dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split));
+
+ helpers::update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ &((&state).into()),
+ &key_store,
+ business_profile.clone(),
+ dynamic_routing_algo_ref.clone(),
+ )
+ .await?;
+
+ Ok(service_api::ApplicationResponse::StatusOk)
+}
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn success_based_routing_update_configs(
state: SessionState,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 9dc56b8bd0a..196db63ff1b 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -969,6 +969,8 @@ pub async fn disable_dynamic_routing_algorithm(
}),
elimination_routing_algorithm: dynamic_routing_algo_ref
.elimination_routing_algorithm,
+ dynamic_routing_volume_split: dynamic_routing_algo_ref
+ .dynamic_routing_volume_split,
},
cache_entries_to_redact,
)
@@ -999,6 +1001,8 @@ pub async fn disable_dynamic_routing_algorithm(
algorithm_id,
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
+ dynamic_routing_volume_split: dynamic_routing_algo_ref
+ .dynamic_routing_volume_split,
elimination_routing_algorithm: Some(
routing_types::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 0fca984cc57..b1e1127787c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1784,6 +1784,10 @@ impl Profile {
web::resource("/toggle")
.route(web::post().to(routing::toggle_elimination_routing)),
),
+ )
+ .service(
+ web::resource("/set_volume_split")
+ .route(web::post().to(routing::set_dynamic_routing_volume_split)),
),
);
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 1c7db127ffc..762a5227207 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -67,7 +67,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::DecisionManagerRetrieveConfig
| Flow::ToggleDynamicRouting
| Flow::UpdateDynamicRoutingConfigs
- | Flow::DecisionManagerUpsertConfig => Self::Routing,
+ | Flow::DecisionManagerUpsertConfig
+ | Flow::VolumeSplitOnRoutingType => Self::Routing,
Flow::RetrieveForexFlow => Self::Forex,
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index d22c5e97490..a9f0bc3a26d 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -1129,3 +1129,51 @@ pub async fn toggle_elimination_routing(
))
.await
}
+
+#[cfg(all(feature = "olap", feature = "v1"))]
+#[instrument(skip_all)]
+pub async fn set_dynamic_routing_volume_split(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_models::routing::DynamicRoutingVolumeSplitQuery>,
+ path: web::Path<routing_types::ToggleDynamicRoutingPath>,
+) -> impl Responder {
+ let flow = Flow::VolumeSplitOnRoutingType;
+ let routing_info = api_models::routing::RoutingVolumeSplit {
+ routing_type: api_models::routing::RoutingType::Dynamic,
+ split: query.into_inner().split,
+ };
+ let payload = api_models::routing::RoutingVolumeSplitWrapper {
+ routing_info,
+ profile_id: path.into_inner().profile_id,
+ };
+
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload.clone(),
+ |state,
+ auth: auth::AuthenticationData,
+ payload: api_models::routing::RoutingVolumeSplitWrapper,
+ _| {
+ routing::configure_dynamic_routing_volume_split(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ payload.profile_id,
+ payload.routing_info,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: payload.profile_id,
+ required_permission: Permission::ProfileRoutingWrite,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 0330c43aa45..27ddc10766d 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -521,6 +521,8 @@ pub enum Flow {
PaymentsPostSessionTokens,
/// Payments start redirection flow
PaymentStartRedirection,
+ /// Volume split on the routing type
+ VolumeSplitOnRoutingType,
}
/// Trait for providing generic behaviour to flow metric
|
2024-11-26T10:16:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Have added a new API for enabling volume split for dynamic routing service
### 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)?
-->
```
curl --location --request POST 'http://localhost:8080/account/sarthak1/business_profile/pro_WlO7KCOeDRB8kWk7MSy1/dynamic_routing/set_volume_split?split=20' \
--header 'api-key: dev_iricUDSeFis6RzTGCcYkOt4wmuBcRfjbVbWXbOUO5996boAgztmtfTKN6HNqerjM'
```
Status in DB -
<img width="1511" alt="image" src="https://github.com/user-attachments/assets/ce1f3149-ffcf-401d-86b8-093e002573af">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
3a3e93cb3be3fc3ffabef2a708b49defabf338a5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6548
|
Bug: refactor(core): add profile_id for default_fallback api
## Description
This will refactor the route routing/default/profile into /default/profile/{profile_id},
Previously the output for this route was the default fallback connectors from all the profiles,
After this refactor it will have the fallback connectors only for the mentioned profile.
|
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 0bd38918ee7..94eb9bd741e 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -909,26 +909,30 @@ pub async fn retrieve_default_fallback_algorithm_for_profile(
}
#[cfg(feature = "v1")]
-
pub async fn retrieve_default_routing_config(
state: SessionState,
+ profile_id: Option<common_utils::id_type::ProfileId>,
merchant_account: domain::MerchantAccount,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
+ let id = profile_id
+ .map(|profile_id| profile_id.get_string_repr().to_owned())
+ .unwrap_or_else(|| merchant_account.get_id().get_string_repr().to_string());
- helpers::get_merchant_default_config(
- db,
- merchant_account.get_id().get_string_repr(),
- transaction_type,
- )
- .await
- .map(|conn_choice| {
- metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
- service_api::ApplicationResponse::Json(conn_choice)
- })
+ helpers::get_merchant_default_config(db, &id, transaction_type)
+ .await
+ .map(|conn_choice| {
+ metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &[],
+ );
+ service_api::ApplicationResponse::Json(conn_choice)
+ })
}
+
#[cfg(feature = "v2")]
pub async fn retrieve_routing_config_under_profile(
state: SessionState,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ee6bd68ac2f..8a12f8a8fdc 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -759,22 +759,14 @@ impl Routing {
},
)))
.service(
- web::resource("/default")
- .route(web::get().to(|state, req| {
- routing::routing_retrieve_default_config(
- state,
- req,
- &TransactionType::Payment,
- )
- }))
- .route(web::post().to(|state, req, payload| {
- routing::routing_update_default_config(
- state,
- req,
- payload,
- &TransactionType::Payment,
- )
- })),
+ web::resource("/default").route(web::post().to(|state, req, payload| {
+ routing::routing_update_default_config(
+ state,
+ req,
+ payload,
+ &TransactionType::Payment,
+ )
+ })),
)
.service(
web::resource("/deactivate").route(web::post().to(|state, req, payload| {
@@ -808,11 +800,7 @@ impl Routing {
)
.service(
web::resource("/default/profile").route(web::get().to(|state, req| {
- routing::routing_retrieve_default_config_for_profiles(
- state,
- req,
- &TransactionType::Payment,
- )
+ routing::routing_retrieve_default_config(state, req, &TransactionType::Payment)
})),
);
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index f0269bd029a..b861b54b5b5 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -565,17 +565,13 @@ pub async fn routing_retrieve_default_config(
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
- routing::retrieve_default_routing_config(state, auth.merchant_account, transaction_type)
+ routing::retrieve_default_routing_config(
+ state,
+ auth.profile_id,
+ auth.merchant_account,
+ transaction_type,
+ )
},
- #[cfg(not(feature = "release"))]
- auth::auth_type(
- &auth::HeaderAuth(auth::ApiKeyAuth),
- &auth::JWTAuth {
- permission: Permission::ProfileRoutingRead,
- },
- req.headers(),
- ),
- #[cfg(feature = "release")]
&auth::JWTAuth {
permission: Permission::ProfileRoutingRead,
},
|
2024-11-12T13:46:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will refactor the route `routing/default/profile`
Previously the output for this route was the default fallback connectors from all the profiles,
After this refactor it will have the fallback connectors only for the mentioned profile. If the `profile_id` is provided by the authentication layer, if not it will behave as previous by taking the `merchant_id` from auth layer.
Moreover we have removed 2 routes from backed as these were not being used(Dahboard as well as internal apis), hence were redundant.
GET `routing/default`
POST `routing/default`
### 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).
-->
Required by our Dashboard to move the api's under profile level
## How did you test 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://127.0.0.1:8080/routing/default/profile' \
--header 'Authorization: Bearer token
```
This should have the connectors from the mentioned profile only.
```
[
{
"connector": "bankofamerica",
"merchant_connector_id": "mca_ADICIF9zh09TjnpUgusU"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
6808272de305c685b7cf948060f006d39cbac60b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6542
|
Bug: ci: run cybersource along with stripe
ci: run cybersource along with stripe
|
2024-11-12T09:40:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
Run Cybersource in parallel along with Stripe.
closes #6542
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
NA
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Let the CI check pass: https://github.com/juspay/hyperswitch/actions/runs/11794582778/job/32975411512?pr=6541
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6536
|
Bug: refactor(routing): remove payment_id from dynamic_routing metrics
|
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 0250d00d1bb..aef89ea8ed9 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -733,7 +733,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
.label
.to_string();
- let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label
+ let (first_success_based_connector, _) = first_success_based_connector_label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
@@ -753,17 +753,12 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
&add_attributes([
("tenant", state.tenant.tenant_id.clone()),
(
- "merchant_id",
- payment_attempt.merchant_id.get_string_repr().to_string(),
- ),
- (
- "profile_id",
- payment_attempt.profile_id.get_string_repr().to_string(),
- ),
- ("merchant_connector_id", merchant_connector_id.to_string()),
- (
- "payment_id",
- payment_attempt.payment_id.get_string_repr().to_string(),
+ "merchant_profile_id",
+ format!(
+ "{}:{}",
+ payment_attempt.merchant_id.get_string_repr(),
+ payment_attempt.profile_id.get_string_repr()
+ ),
),
(
"success_based_routing_connector",
|
2024-11-11T13:52:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will remove payment_id from being pushed to dynamic_routing metrics
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 can be tested on SBX in the dynamic_routing Dashboard present on grafana dashboard,
There shouldn't be payment_id and the merchant_id should be merged with profile_id
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0a506b1729a27e47543cf24f64fbad08479d8dec
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6561
|
Bug: Create toggle and update endpoints for ER
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 1494908c5fc..68631872aa7 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -1278,7 +1278,7 @@
],
"summary": "Routing - Create",
"description": "Create a routing algorithm",
- "operationId": "Create a routing algprithm",
+ "operationId": "Create a routing algorithm",
"requestBody": {
"content": {
"application/json": {
diff --git a/crates/api_models/src/events/routing.rs b/crates/api_models/src/events/routing.rs
index ffa5e008f0a..87e7fa27885 100644
--- a/crates/api_models/src/events/routing.rs
+++ b/crates/api_models/src/events/routing.rs
@@ -6,7 +6,7 @@ use crate::routing::{
RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery,
RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, SuccessBasedRoutingConfig,
SuccessBasedRoutingPayloadWrapper, SuccessBasedRoutingUpdateConfigQuery,
- ToggleSuccessBasedRoutingQuery, ToggleSuccessBasedRoutingWrapper,
+ ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper,
};
impl ApiEventMetric for RoutingKind {
@@ -79,7 +79,7 @@ impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper {
}
}
-impl ApiEventMetric for ToggleSuccessBasedRoutingQuery {
+impl ApiEventMetric for ToggleDynamicRoutingQuery {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Routing)
}
@@ -97,7 +97,7 @@ impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper {
}
}
-impl ApiEventMetric for ToggleSuccessBasedRoutingWrapper {
+impl ApiEventMetric for ToggleDynamicRoutingWrapper {
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 389af3dab7b..3b09dc8eb3b 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -523,6 +523,92 @@ pub struct DynamicAlgorithmWithTimestamp<T> {
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
+ pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
+}
+
+pub trait DynamicRoutingAlgoAccessor {
+ fn get_algorithm_id_with_timestamp(
+ self,
+ ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>;
+ fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures;
+}
+
+impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm {
+ fn get_algorithm_id_with_timestamp(
+ self,
+ ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
+ self.algorithm_id_with_timestamp
+ }
+ fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
+ &mut self.enabled_feature
+ }
+}
+
+impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
+ fn get_algorithm_id_with_timestamp(
+ self,
+ ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
+ self.algorithm_id_with_timestamp
+ }
+ fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
+ &mut self.enabled_feature
+ }
+}
+
+impl EliminationRoutingAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
+impl SuccessBasedAlgorithm {
+ pub fn new(
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
+ common_utils::id_type::RoutingId,
+ >,
+ ) -> Self {
+ Self {
+ algorithm_id_with_timestamp,
+ enabled_feature: DynamicRoutingFeatures::None,
+ }
+ }
+}
+
+impl DynamicRoutingAlgorithmRef {
+ pub fn update(&mut self, new: Self) {
+ if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
+ self.elimination_routing_algorithm = Some(elimination_routing_algorithm)
+ }
+ if let Some(success_based_algorithm) = new.success_based_algorithm {
+ self.success_based_algorithm = Some(success_based_algorithm)
+ }
+ }
+
+ pub fn update_specific_ref(
+ &mut self,
+ algo_type: DynamicRoutingType,
+ feature_to_enable: DynamicRoutingFeatures,
+ ) {
+ match algo_type {
+ DynamicRoutingType::SuccessRateBasedRouting => {
+ self.success_based_algorithm
+ .as_mut()
+ .map(|algo| algo.enabled_feature = feature_to_enable);
+ }
+ DynamicRoutingType::EliminationRouting => {
+ self.elimination_routing_algorithm
+ .as_mut()
+ .map(|algo| algo.enabled_feature = feature_to_enable);
+ }
+ }
+ }
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -530,11 +616,25 @@ pub struct SuccessBasedAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
- pub enabled_feature: SuccessBasedRoutingFeatures,
+ pub enabled_feature: DynamicRoutingFeatures,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct EliminationRoutingAlgorithm {
+ pub algorithm_id_with_timestamp:
+ DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
+ #[serde(default)]
+ pub enabled_feature: DynamicRoutingFeatures,
+}
+
+impl EliminationRoutingAlgorithm {
+ pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
+ self.enabled_feature = feature_to_enable
+ }
}
impl SuccessBasedAlgorithm {
- pub fn update_enabled_features(&mut self, feature_to_enable: SuccessBasedRoutingFeatures) {
+ pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
@@ -543,26 +643,40 @@ impl DynamicRoutingAlgorithmRef {
pub fn update_algorithm_id(
&mut self,
new_id: common_utils::id_type::RoutingId,
- enabled_feature: SuccessBasedRoutingFeatures,
+ enabled_feature: DynamicRoutingFeatures,
+ dynamic_routing_type: DynamicRoutingType,
) {
- self.success_based_algorithm = Some(SuccessBasedAlgorithm {
- algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
- algorithm_id: Some(new_id),
- timestamp: common_utils::date_time::now_unix_timestamp(),
- },
- enabled_feature,
- })
+ match dynamic_routing_type {
+ DynamicRoutingType::SuccessRateBasedRouting => {
+ self.success_based_algorithm = Some(SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(new_id),
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ },
+ enabled_feature,
+ })
+ }
+ DynamicRoutingType::EliminationRouting => {
+ self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(new_id),
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ },
+ enabled_feature,
+ })
+ }
+ };
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
-pub struct ToggleSuccessBasedRoutingQuery {
- pub enable: SuccessBasedRoutingFeatures,
+pub struct ToggleDynamicRoutingQuery {
+ pub enable: DynamicRoutingFeatures,
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
-pub enum SuccessBasedRoutingFeatures {
+pub enum DynamicRoutingFeatures {
Metrics,
DynamicConnectorSelection,
#[default]
@@ -578,26 +692,52 @@ pub struct SuccessBasedRoutingUpdateConfigQuery {
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
-pub struct ToggleSuccessBasedRoutingWrapper {
+pub struct ToggleDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
- pub feature_to_enable: SuccessBasedRoutingFeatures,
+ pub feature_to_enable: DynamicRoutingFeatures,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
-pub struct ToggleSuccessBasedRoutingPath {
+pub struct ToggleDynamicRoutingPath {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct EliminationRoutingConfig {
+ pub params: Option<Vec<DynamicRoutingConfigParams>>,
+ // pub labels: Option<Vec<String>>,
+ pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+pub struct EliminationAnalyserConfig {
+ pub bucket_size: Option<u32>,
+ pub bucket_ttl_in_mins: Option<f64>,
+}
+
+impl Default for EliminationRoutingConfig {
+ fn default() -> Self {
+ Self {
+ params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
+ elimination_analyser_config: Some(EliminationAnalyserConfig {
+ bucket_size: Some(5),
+ bucket_ttl_in_mins: Some(2.0),
+ }),
+ }
+ }
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct SuccessBasedRoutingConfig {
- pub params: Option<Vec<SuccessBasedRoutingConfigParams>>,
+ pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub config: Option<SuccessBasedRoutingConfigBody>,
}
impl Default for SuccessBasedRoutingConfig {
fn default() -> Self {
Self {
- params: Some(vec![SuccessBasedRoutingConfigParams::PaymentMethod]),
+ params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(2),
default_success_rate: Some(100.0),
@@ -612,7 +752,7 @@ impl Default for SuccessBasedRoutingConfig {
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)]
-pub enum SuccessBasedRoutingConfigParams {
+pub enum DynamicRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
AuthenticationType,
@@ -643,6 +783,12 @@ pub struct SuccessBasedRoutingPayloadWrapper {
pub profile_id: common_utils::id_type::ProfileId,
}
+#[derive(Debug, Clone, strum::Display, serde::Serialize, serde::Deserialize)]
+pub enum DynamicRoutingType {
+ SuccessRateBasedRouting,
+ EliminationRouting,
+}
+
impl SuccessBasedRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(params) = new.params {
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index ed6efea27f8..4ec1bb22b4b 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -575,7 +575,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
- api_models::routing::SuccessBasedRoutingFeatures,
+ api_models::routing::DynamicRoutingFeatures,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
@@ -586,8 +586,8 @@ 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::ToggleSuccessBasedRoutingPath,
+ api_models::routing::ToggleDynamicRoutingQuery,
+ api_models::routing::ToggleDynamicRoutingPath,
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 67a22c2ca64..08d2e46a616 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -37,7 +37,7 @@ pub async fn routing_create_config() {}
(status = 403, description = "Forbidden"),
),
tag = "Routing",
- operation_id = "Create a routing algprithm",
+ operation_id = "Create a routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
@@ -266,7 +266,7 @@ pub async fn routing_update_default_config_for_profile() {}
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
- ("enable" = SuccessBasedRoutingFeatures, Query, description = "Feature to enable for success based routing"),
+ ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
@@ -277,7 +277,33 @@ pub async fn routing_update_default_config_for_profile() {}
(status = 403, description = "Forbidden"),
),
tag = "Routing",
- operation_id = "Toggle success based dynamic routing algprithm",
+ operation_id = "Toggle success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_success_based_routing() {}
+
+#[cfg(feature = "v1")]
+/// Routing - Toggle elimination routing for profile
+///
+/// Create a elimination based dynamic routing algorithm
+#[utoipa::path(
+ post,
+ path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/elimination/toggle",
+ params(
+ ("account_id" = String, Path, description = "Merchant id"),
+ ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
+ ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based 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 elimination routing algorithm",
+ security(("api_key" = []), ("jwt_key" = []))
+)]
+pub async fn toggle_elimination_routing() {}
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 28321529ef2..2fb49c37d22 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -1263,7 +1263,7 @@ pub async fn perform_success_based_routing(
)?;
if success_based_algo_ref.enabled_feature
- == api_routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection
+ == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing success_based_routing for profile {}",
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 348f5229b75..9318e0c5b9f 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -452,6 +452,16 @@ pub async fn link_routing_config(
},
enabled_feature: _
}) if id == &algorithm_id
+ ) || matches!(
+ dynamic_routing_ref.elimination_routing_algorithm,
+ Some(routing::EliminationRoutingAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(ref id),
+ timestamp: _
+ },
+ enabled_feature: _
+ }) if id == &algorithm_id
),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
@@ -470,7 +480,9 @@ pub async fn link_routing_config(
"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
+ routing_types::DynamicRoutingType::SuccessRateBasedRouting,
);
+
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
@@ -1185,13 +1197,16 @@ pub async fn update_default_routing_config_for_profile(
))
}
+// Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table
+// and update the same in business profile table.
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-pub async fn toggle_success_based_routing(
+pub async fn toggle_specific_dynamic_routing(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- feature_to_enable: routing::SuccessBasedRoutingFeatures,
+ feature_to_enable: routing::DynamicRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
+ dynamic_routing_type: routing::DynamicRoutingType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
&metrics::CONTEXT,
@@ -1214,170 +1229,44 @@ pub async fn toggle_success_based_routing(
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();
+ let 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();
match feature_to_enable {
- routing::SuccessBasedRoutingFeatures::Metrics
- | routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection => {
- if let Some(ref mut algo_with_timestamp) =
- success_based_dynamic_routing_algo_ref.success_based_algorithm
- {
- match algo_with_timestamp
- .algorithm_id_with_timestamp
- .algorithm_id
- .clone()
- {
- Some(algorithm_id) => {
- // algorithm is already present in profile
- if algo_with_timestamp.enabled_feature == feature_to_enable {
- // algorithm already has the required feature
- Err(errors::ApiErrorResponse::PreconditionFailed {
- message: "Success rate based routing is already enabled"
- .to_string(),
- })?
- } else {
- // enable the requested feature for the algorithm
- algo_with_timestamp.update_enabled_features(feature_to_enable);
- 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,
- success_based_dynamic_routing_algo_ref,
- )
- .await?;
-
- 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(response))
- }
- }
- None => {
- // algorithm isn't present in profile
- helpers::default_success_based_routing_setup(
- &state,
- key_store,
- business_profile,
- feature_to_enable,
- merchant_account.get_id().to_owned(),
- success_based_dynamic_routing_algo_ref,
- )
- .await
- }
- }
- } else {
- // algorithm isn't present in profile
- helpers::default_success_based_routing_setup(
- &state,
- key_store,
- business_profile,
- feature_to_enable,
- merchant_account.get_id().to_owned(),
- success_based_dynamic_routing_algo_ref,
- )
- .await
- }
+ routing::DynamicRoutingFeatures::Metrics
+ | routing::DynamicRoutingFeatures::DynamicConnectorSelection => {
+ // occurs when algorithm is already present in the db
+ // 1. If present with same feature then return response as already enabled
+ // 2. Else update the feature and persist the same on db
+ // 3. If not present in db then create a new default entry
+ helpers::enable_dynamic_routing_algorithm(
+ &state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ )
+ .await
}
- routing::SuccessBasedRoutingFeatures::None => {
- // disable success based routing for the requested profile
- 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_with_timestamp.algorithm_id
- {
- let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef {
- success_based_algorithm: Some(routing::SuccessBasedAlgorithm {
- algorithm_id_with_timestamp:
- routing_types::DynamicAlgorithmWithTimestamp {
- algorithm_id: None,
- timestamp,
- },
- enabled_feature: routing::SuccessBasedRoutingFeatures::None,
- }),
- };
-
- // redact cache for success based routing configs
- let cache_key = format!(
- "{}_{}",
- business_profile.get_id().get_string_repr(),
- algorithm_id.get_string_repr()
- );
- let cache_entries_to_redact =
- vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
- cache_key.into(),
- )];
- let _ = cache::publish_into_redact_channel(
- state.store.get_cache_store().as_ref(),
- cache_entries_to_redact,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to publish into the redact channel for evicting the success based routing config cache")?;
-
- 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: "Success rate based routing is already disabled".to_string(),
- })?,
- }
+ routing::DynamicRoutingFeatures::None => {
+ // disable specific dynamic routing for the requested profile
+ helpers::disable_dynamic_routing_algorithm(
+ &state,
+ key_store,
+ business_profile,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ )
+ .await
}
}
}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 264328796c8..b445627446e 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -26,6 +26,8 @@ use router_env::{instrument, metrics::add_attributes, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
+#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+use crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
use crate::types::domain::MerchantConnectorAccount;
use crate::{
@@ -39,6 +41,8 @@ use crate::{
use crate::{core::metrics as core_metrics, routes::metrics, types::transformers::ForeignInto};
pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
"Success rate based dynamic routing algorithm";
+pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
+ "Elimination based dynamic routing algorithm";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
@@ -263,9 +267,9 @@ pub async fn update_business_profile_active_dynamic_algorithm_ref(
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
- dynamic_routing_algorithm: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef,
) -> RouterResult<()> {
- let ref_val = dynamic_routing_algorithm
+ let ref_val = dynamic_routing_algorithm_ref
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert dynamic routing ref to value")?;
@@ -662,7 +666,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
- if success_based_algo_ref.enabled_feature != routing_types::SuccessBasedRoutingFeatures::None {
+ if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = state
.grpc_client
.dynamic_routing
@@ -912,34 +916,303 @@ pub fn generate_tenant_business_profile_id(
format!("{}:{}", redis_key_prefix, business_profile_id)
}
-/// default config setup for success_based_routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn disable_dynamic_routing_algorithm(
+ state: &SessionState,
+ key_store: domain::MerchantKeyStore,
+ business_profile: domain::Profile,
+ dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_type: routing_types::DynamicRoutingType,
+) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
+ let db = state.store.as_ref();
+ let key_manager_state = &state.into();
+ let timestamp = common_utils::date_time::now_unix_timestamp();
+ let profile_id = business_profile
+ .get_id()
+ .clone()
+ .get_string_repr()
+ .to_owned();
+ let (algorithm_id, dynamic_routing_algorithm, cache_entries_to_redact) =
+ match dynamic_routing_type {
+ routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
+ let Some(algorithm_ref) = dynamic_routing_algo_ref.success_based_algorithm else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Success rate based routing is already disabled".to_string(),
+ })?
+ };
+ let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
+ else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ };
+
+ let cache_key = format!(
+ "{}_{}",
+ business_profile.get_id().get_string_repr(),
+ algorithm_id.get_string_repr()
+ );
+ let cache_entries_to_redact =
+ vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
+ cache_key.into(),
+ )];
+ (
+ algorithm_id,
+ routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: None,
+ timestamp,
+ },
+ enabled_feature: routing_types::DynamicRoutingFeatures::None,
+ }),
+ elimination_routing_algorithm: dynamic_routing_algo_ref
+ .elimination_routing_algorithm,
+ },
+ cache_entries_to_redact,
+ )
+ }
+ routing_types::DynamicRoutingType::EliminationRouting => {
+ let Some(algorithm_ref) = dynamic_routing_algo_ref.elimination_routing_algorithm
+ else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Elimination routing is already disabled".to_string(),
+ })?
+ };
+ let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id
+ else {
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Algorithm is already inactive".to_string(),
+ })?
+ };
+ let cache_key = format!(
+ "{}_{}",
+ business_profile.get_id().get_string_repr(),
+ algorithm_id.get_string_repr()
+ );
+ let cache_entries_to_redact =
+ vec![cache::CacheKind::EliminationBasedDynamicRoutingCache(
+ cache_key.into(),
+ )];
+ (
+ algorithm_id,
+ routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm,
+ elimination_routing_algorithm: Some(
+ routing_types::EliminationRoutingAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: None,
+ timestamp,
+ },
+ enabled_feature: routing_types::DynamicRoutingFeatures::None,
+ },
+ ),
+ },
+ cache_entries_to_redact,
+ )
+ }
+ };
+
+ // redact cache for dynamic routing config
+ let _ = cache::publish_into_redact_channel(
+ state.store.get_cache_store().as_ref(),
+ cache_entries_to_redact,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to publish into the redact channel for evicting the dynamic routing config cache",
+ )?;
+
+ 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();
+ update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ dynamic_routing_algorithm,
+ )
+ .await?;
+
+ core_metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id)]),
+ );
+
+ Ok(ApplicationResponse::Json(response))
+}
+
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn enable_dynamic_routing_algorithm(
+ state: &SessionState,
+ key_store: domain::MerchantKeyStore,
+ business_profile: domain::Profile,
+ feature_to_enable: routing_types::DynamicRoutingFeatures,
+ dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_type: routing_types::DynamicRoutingType,
+) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
+ let dynamic_routing = dynamic_routing_algo_ref.clone();
+ match dynamic_routing_type {
+ routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
+ enable_specific_routing_algorithm(
+ state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ dynamic_routing.success_based_algorithm,
+ )
+ .await
+ }
+ routing_types::DynamicRoutingType::EliminationRouting => {
+ enable_specific_routing_algorithm(
+ state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ dynamic_routing.elimination_routing_algorithm,
+ )
+ .await
+ }
+ }
+}
+
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn enable_specific_routing_algorithm<A>(
+ state: &SessionState,
+ key_store: domain::MerchantKeyStore,
+ business_profile: domain::Profile,
+ feature_to_enable: routing_types::DynamicRoutingFeatures,
+ mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_type: routing_types::DynamicRoutingType,
+ algo_type: Option<A>,
+) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>>
+where
+ A: routing_types::DynamicRoutingAlgoAccessor + Clone + std::fmt::Debug,
+{
+ // Algorithm wasn't created yet
+ let Some(mut algo_type) = algo_type else {
+ return default_specific_dynamic_routing_setup(
+ state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ )
+ .await;
+ };
+
+ // Algorithm was in disabled state
+ let Some(algo_type_algorithm_id) = algo_type
+ .clone()
+ .get_algorithm_id_with_timestamp()
+ .algorithm_id
+ else {
+ return default_specific_dynamic_routing_setup(
+ state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ dynamic_routing_algo_ref,
+ dynamic_routing_type,
+ )
+ .await;
+ };
+ let db = state.store.as_ref();
+ let profile_id = business_profile.get_id().clone();
+ let algo_type_enabled_features = algo_type.get_enabled_features();
+ if *algo_type_enabled_features == feature_to_enable {
+ // algorithm already has the required feature
+ return Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: format!("{} is already enabled", dynamic_routing_type),
+ }
+ .into());
+ };
+ *algo_type_enabled_features = feature_to_enable.clone();
+ dynamic_routing_algo_ref
+ .update_specific_ref(dynamic_routing_type.clone(), feature_to_enable.clone());
+ update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ &state.into(),
+ &key_store,
+ business_profile,
+ dynamic_routing_algo_ref.clone(),
+ )
+ .await?;
+
+ let routing_algorithm = db
+ .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algo_type_algorithm_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
+ let updated_routing_record = routing_algorithm.foreign_into();
+ core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_owned())]),
+ );
+ Ok(ApplicationResponse::Json(updated_routing_record))
+}
+
#[cfg(feature = "v1")]
#[instrument(skip_all)]
-pub async fn default_success_based_routing_setup(
+pub async fn default_specific_dynamic_routing_setup(
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: domain::Profile,
- feature_to_enable: routing_types::SuccessBasedRoutingFeatures,
- merchant_id: id_type::MerchantId,
- mut success_based_dynamic_routing_algo: routing_types::DynamicRoutingAlgorithmRef,
+ feature_to_enable: routing_types::DynamicRoutingFeatures,
+ mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ dynamic_routing_type: routing_types::DynamicRoutingType,
) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &state.into();
- let profile_id = business_profile.get_id().to_owned();
- let default_success_based_routing_config = routing_types::SuccessBasedRoutingConfig::default();
+ let profile_id = business_profile.get_id().clone();
+ let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
- let algo = routing_algorithm::RoutingAlgorithm {
- algorithm_id: algorithm_id.clone(),
- profile_id: profile_id.clone(),
- merchant_id,
- name: SUCCESS_BASED_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 algo = match dynamic_routing_type {
+ routing_types::DynamicRoutingType::SuccessRateBasedRouting => {
+ let default_success_based_routing_config =
+ routing_types::SuccessBasedRoutingConfig::default();
+ routing_algorithm::RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: profile_id.clone(),
+ merchant_id,
+ name: SUCCESS_BASED_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,
+ }
+ }
+ routing_types::DynamicRoutingType::EliminationRouting => {
+ let default_elimination_routing_config =
+ routing_types::EliminationRoutingConfig::default();
+ routing_algorithm::RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: profile_id.clone(),
+ merchant_id,
+ name: ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
+ description: None,
+ kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
+ algorithm_data: serde_json::json!(default_elimination_routing_config),
+ created_at: timestamp,
+ modified_at: timestamp,
+ algorithm_for: common_enums::TransactionType::Payment,
+ }
+ }
};
let record = db
@@ -948,13 +1221,17 @@ pub async fn default_success_based_routing_setup(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
- success_based_dynamic_routing_algo.update_algorithm_id(algorithm_id, feature_to_enable);
+ dynamic_routing_algo_ref.update_algorithm_id(
+ algorithm_id,
+ feature_to_enable,
+ dynamic_routing_type,
+ );
update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
&key_store,
business_profile,
- success_based_dynamic_routing_algo,
+ dynamic_routing_algo_ref,
)
.await?;
@@ -1001,35 +1278,35 @@ impl SuccessBasedRoutingConfigParamsInterpolator {
pub fn get_string_val(
&self,
- params: &Vec<routing_types::SuccessBasedRoutingConfigParams>,
+ params: &Vec<routing_types::DynamicRoutingConfigParams>,
) -> String {
let mut parts: Vec<String> = Vec::new();
for param in params {
let val = match param {
- routing_types::SuccessBasedRoutingConfigParams::PaymentMethod => self
+ routing_types::DynamicRoutingConfigParams::PaymentMethod => self
.payment_method
.as_ref()
.map_or(String::new(), |pm| pm.to_string()),
- routing_types::SuccessBasedRoutingConfigParams::PaymentMethodType => self
+ routing_types::DynamicRoutingConfigParams::PaymentMethodType => self
.payment_method_type
.as_ref()
.map_or(String::new(), |pmt| pmt.to_string()),
- routing_types::SuccessBasedRoutingConfigParams::AuthenticationType => self
+ routing_types::DynamicRoutingConfigParams::AuthenticationType => self
.authentication_type
.as_ref()
.map_or(String::new(), |at| at.to_string()),
- routing_types::SuccessBasedRoutingConfigParams::Currency => self
+ routing_types::DynamicRoutingConfigParams::Currency => self
.currency
.as_ref()
.map_or(String::new(), |cur| cur.to_string()),
- routing_types::SuccessBasedRoutingConfigParams::Country => self
+ routing_types::DynamicRoutingConfigParams::Country => self
.country
.as_ref()
.map_or(String::new(), |cn| cn.to_string()),
- routing_types::SuccessBasedRoutingConfigParams::CardNetwork => {
+ routing_types::DynamicRoutingConfigParams::CardNetwork => {
self.card_network.clone().unwrap_or_default()
}
- routing_types::SuccessBasedRoutingConfigParams::CardBin => {
+ routing_types::DynamicRoutingConfigParams::CardBin => {
self.card_bin.clone().unwrap_or_default()
}
};
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1584cfae2b9..432a46b4bda 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1752,9 +1752,9 @@ impl Profile {
#[cfg(feature = "dynamic_routing")]
{
- route =
- route.service(
- web::scope("/{profile_id}/dynamic_routing").service(
+ route = route.service(
+ web::scope("/{profile_id}/dynamic_routing")
+ .service(
web::scope("/success_based")
.service(
web::resource("/toggle")
@@ -1767,8 +1767,14 @@ impl Profile {
)
}),
)),
+ )
+ .service(
+ web::scope("/elimination").service(
+ web::resource("/toggle")
+ .route(web::post().to(routing::toggle_elimination_routing)),
+ ),
),
- );
+ );
}
route = route.service(
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index cb7744f5200..d22c5e97490 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -1014,11 +1014,11 @@ pub async fn routing_update_default_config_for_profile(
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>,
+ query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>,
+ path: web::Path<routing_types::ToggleDynamicRoutingPath>,
) -> impl Responder {
let flow = Flow::ToggleDynamicRouting;
- let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper {
+ let wrapper = routing_types::ToggleDynamicRoutingWrapper {
feature_to_enable: query.into_inner().enable,
profile_id: path.into_inner().profile_id,
};
@@ -1029,14 +1029,15 @@ pub async fn toggle_success_based_routing(
wrapper.clone(),
|state,
auth: auth::AuthenticationData,
- wrapper: routing_types::ToggleSuccessBasedRoutingWrapper,
+ wrapper: routing_types::ToggleDynamicRoutingWrapper,
_| {
- routing::toggle_success_based_routing(
+ routing::toggle_specific_dynamic_routing(
state,
auth.merchant_account,
auth.key_store,
wrapper.feature_to_enable,
wrapper.profile_id,
+ api_models::routing::DynamicRoutingType::SuccessRateBasedRouting,
)
},
auth::auth_type(
@@ -1085,3 +1086,46 @@ pub async fn success_based_routing_update_configs(
))
.await
}
+#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn toggle_elimination_routing(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>,
+ path: web::Path<routing_types::ToggleDynamicRoutingPath>,
+) -> impl Responder {
+ let flow = Flow::ToggleDynamicRouting;
+ let wrapper = routing_types::ToggleDynamicRoutingWrapper {
+ feature_to_enable: query.into_inner().enable,
+ 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::ToggleDynamicRoutingWrapper,
+ _| {
+ routing::toggle_specific_dynamic_routing(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ wrapper.feature_to_enable,
+ wrapper.profile_id,
+ api_models::routing::DynamicRoutingType::EliminationRouting,
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ &auth::JWTAuthProfileFromRoute {
+ profile_id: wrapper.profile_id,
+ required_permission: Permission::ProfileRoutingWrite,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 69931057959..7a452106b2b 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -72,7 +72,7 @@ pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> = Lazy::new(|| {
)
});
-/// Dynamic Algorithm Cache
+/// Success based Dynamic Algorithm Cache
pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
Cache::new(
"SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE",
@@ -82,6 +82,16 @@ pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
)
});
+/// Elimination based Dynamic Algorithm Cache
+pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| {
+ Cache::new(
+ "ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE",
+ CACHE_TTL,
+ CACHE_TTI,
+ Some(MAX_CAPACITY),
+ )
+});
+
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
@@ -102,6 +112,7 @@ pub enum CacheKind<'a> {
Surcharge(Cow<'a, str>),
CGraph(Cow<'a, str>),
SuccessBasedDynamicRoutingCache(Cow<'a, str>),
+ EliminationBasedDynamicRoutingCache(Cow<'a, str>),
PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 6a2012f9b26..42ad2ae0795 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -6,8 +6,8 @@ use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
- DECISION_MANAGER_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE,
- SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
+ DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE,
+ ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
@@ -138,6 +138,15 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
.await;
key
}
+ CacheKind::EliminationBasedDynamicRoutingCache(key) => {
+ ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: message.tenant.clone(),
+ })
+ .await;
+ key
+ }
CacheKind::SuccessBasedDynamicRoutingCache(key) => {
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
@@ -205,6 +214,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
prefix: message.tenant.clone(),
})
.await;
+ ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: message.tenant.clone(),
+ })
+ .await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
|
2024-11-14T08:21:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR will add route to enable Elimination based dynamic routing for specific profiles.
```
curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=none' \
--header 'api-key: API_KEY'
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Testing Scenarios:
1. enable elimination routing and check Profile table for the following value:
```
dynamic_routing_algorithm |
{"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_nkajfnkjanf131231","timestamp":1732569427},"enabled_feature":"metrics"}}
```
can be enabled by this curl:
```
curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=metrics' \
--header 'api-key: API_KEY'
```
2. disable elimination routing and check profile table(can be disabled by passing enable as none),
Note: SR shouldn't be removed.
```
dynamic_routing_algorithm |
{"success_based_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":"routing_2hS6Dn3XRjICecmNZg5s","timestamp":1732569416},"enabled_feature":"metrics"},"elimination_routing_algorithm":{"algorithm_id_with_timestamp":{"algorithm_id":null,"timestamp":1732569427},"enabled_feature":"none"}}
```
can be disabled by this curl:
```
curl --location --request POST 'http://localhost:8080/account/MERCHANT_ID/business_profile/PROFILE_ID/dynamic_routing/elimination/toggle?enable=none' \
--header 'api-key: API_KEY'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6563
|
Bug: Integration of ER in core flow
|
diff --git a/config/development.toml b/config/development.toml
index 3a041db3574..c83713e2a07 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -991,7 +991,7 @@ connector_list = "cybersource"
[grpc_client.dynamic_routing_client]
host = "localhost"
-port = 7000
+port = 8000
service = "dynamo"
[theme.storage]
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 693e9585ddb..d3529edd29e 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -811,7 +811,7 @@ pub struct EliminationRoutingConfig {
pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
}
-#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)]
pub struct EliminationAnalyserConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index cb711c52515..87c64747c69 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -7795,6 +7795,17 @@ pub enum ErrorCategory {
ProcessorDeclineIncorrectData,
}
+impl ErrorCategory {
+ pub fn should_perform_elimination_routing(self) -> bool {
+ match self {
+ Self::ProcessorDowntime | Self::ProcessorDeclineUnauthorized => true,
+ Self::IssueWithPaymentMethod
+ | Self::ProcessorDeclineIncorrectData
+ | Self::FrmDecline => false,
+ }
+ }
+}
+
#[derive(
Clone,
Debug,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index a574d84fdcb..9621e619148 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -387,6 +387,18 @@ pub enum RoutingError {
SuccessRateCalculationError,
#[error("Success rate client from dynamic routing gRPC service not initialized")]
SuccessRateClientInitializationError,
+ #[error("Elimination client from dynamic routing gRPC service not initialized")]
+ EliminationClientInitializationError,
+ #[error("Unable to analyze elimination routing config from dynamic routing service")]
+ EliminationRoutingCalculationError,
+ #[error("Params not found in elimination based routing config")]
+ EliminationBasedRoutingParamsNotFoundError,
+ #[error("Unable to retrieve elimination based routing config")]
+ EliminationRoutingConfigError,
+ #[error(
+ "Invalid elimination based connector label received from dynamic routing service: '{0}'"
+ )]
+ InvalidEliminationBasedConnectorLabel(String),
#[error("Unable to convert from '{from}' to '{to}'")]
GenericConversionError { from: String, to: String },
#[error("Invalid success based connector label received from dynamic routing service: '{0}'")]
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index f5f95288eea..7988a625e7a 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1411,7 +1411,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.as_mut()
.map(|info| info.status = status)
});
- let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {
+
+ // TODO: refactor of gsm_error_category with respective feature flag
+ #[allow(unused_variables)]
+ let (capture_update, mut payment_attempt_update, gsm_error_category) = match router_data
+ .response
+ .clone()
+ {
Err(err) => {
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
@@ -1420,123 +1426,127 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
} else {
None
};
- let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
- Some(multiple_capture_data) => {
- let capture_update = storage::CaptureUpdate::ErrorUpdate {
- status: match err.status_code {
- 500..=511 => enums::CaptureStatus::Pending,
- _ => enums::CaptureStatus::Failed,
- },
- error_code: Some(err.code),
- error_message: Some(err.message),
- error_reason: err.reason,
- };
- let capture_update_list = vec![(
- multiple_capture_data.get_latest_capture().clone(),
- capture_update,
- )];
- (
- Some((multiple_capture_data, capture_update_list)),
- auth_update.map(|auth_type| {
- storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
- authentication_type: auth_type,
- updated_by: storage_scheme.to_string(),
- }
- }),
- )
- }
- None => {
- let connector_name = router_data.connector.to_string();
- let flow_name = core_utils::get_flow_name::<F>()?;
- let option_gsm = payments_helpers::get_gsm_record(
- state,
- Some(err.code.clone()),
- Some(err.message.clone()),
- connector_name,
- flow_name.clone(),
- )
- .await;
-
- let gsm_unified_code =
- option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
- let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
-
- let (unified_code, unified_message) = if let Some((code, message)) =
- gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())
- {
- (code.to_owned(), message.to_owned())
- } else {
+ let (capture_update, attempt_update, gsm_error_category) =
+ match payment_data.multiple_capture_data {
+ Some(multiple_capture_data) => {
+ let capture_update = storage::CaptureUpdate::ErrorUpdate {
+ status: match err.status_code {
+ 500..=511 => enums::CaptureStatus::Pending,
+ _ => enums::CaptureStatus::Failed,
+ },
+ error_code: Some(err.code),
+ error_message: Some(err.message),
+ error_reason: err.reason,
+ };
+ let capture_update_list = vec![(
+ multiple_capture_data.get_latest_capture().clone(),
+ capture_update,
+ )];
(
- consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
- consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
+ Some((multiple_capture_data, capture_update_list)),
+ auth_update.map(|auth_type| {
+ storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
+ authentication_type: auth_type,
+ updated_by: storage_scheme.to_string(),
+ }
+ }),
+ None,
)
- };
- let unified_translated_message = locale
- .as_ref()
- .async_and_then(|locale_str| async {
- payments_helpers::get_unified_translation(
- state,
- unified_code.to_owned(),
- unified_message.to_owned(),
- locale_str.to_owned(),
+ }
+ None => {
+ let connector_name = router_data.connector.to_string();
+ let flow_name = core_utils::get_flow_name::<F>()?;
+ let option_gsm = payments_helpers::get_gsm_record(
+ state,
+ Some(err.code.clone()),
+ Some(err.message.clone()),
+ connector_name,
+ flow_name.clone(),
+ )
+ .await;
+
+ let gsm_unified_code =
+ option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
+ let gsm_unified_message =
+ option_gsm.clone().and_then(|gsm| gsm.unified_message);
+
+ let (unified_code, unified_message) = if let Some((code, message)) =
+ gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())
+ {
+ (code.to_owned(), message.to_owned())
+ } else {
+ (
+ consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
+ consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
)
+ };
+ let unified_translated_message = locale
+ .as_ref()
+ .async_and_then(|locale_str| async {
+ payments_helpers::get_unified_translation(
+ state,
+ unified_code.to_owned(),
+ unified_message.to_owned(),
+ locale_str.to_owned(),
+ )
+ .await
+ })
.await
- })
- .await
- .or(Some(unified_message));
+ .or(Some(unified_message));
- let status = match err.attempt_status {
- // Use the status sent by connector in error_response if it's present
- Some(status) => status,
- None =>
- // mark previous attempt status for technical failures in PSync flow
- {
- if flow_name == "PSync" {
- match err.status_code {
- // marking failure for 2xx because this is genuine payment failure
- 200..=299 => enums::AttemptStatus::Failure,
- _ => router_data.status,
- }
- } else if flow_name == "Capture" {
- match err.status_code {
- 500..=511 => enums::AttemptStatus::Pending,
- // don't update the status for 429 error status
- 429 => router_data.status,
- _ => enums::AttemptStatus::Failure,
- }
- } else {
- match err.status_code {
- 500..=511 => enums::AttemptStatus::Pending,
- _ => enums::AttemptStatus::Failure,
+ let status = match err.attempt_status {
+ // Use the status sent by connector in error_response if it's present
+ Some(status) => status,
+ None =>
+ // mark previous attempt status for technical failures in PSync flow
+ {
+ if flow_name == "PSync" {
+ match err.status_code {
+ // marking failure for 2xx because this is genuine payment failure
+ 200..=299 => enums::AttemptStatus::Failure,
+ _ => router_data.status,
+ }
+ } else if flow_name == "Capture" {
+ match err.status_code {
+ 500..=511 => enums::AttemptStatus::Pending,
+ // don't update the status for 429 error status
+ 429 => router_data.status,
+ _ => enums::AttemptStatus::Failure,
+ }
+ } else {
+ match err.status_code {
+ 500..=511 => enums::AttemptStatus::Pending,
+ _ => enums::AttemptStatus::Failure,
+ }
}
}
- }
- };
- (
- None,
- Some(storage::PaymentAttemptUpdate::ErrorUpdate {
- connector: None,
- status,
- error_message: Some(Some(err.message)),
- error_code: Some(Some(err.code)),
- error_reason: Some(err.reason),
- amount_capturable: router_data
- .request
- .get_amount_capturable(&payment_data, status)
- .map(MinorUnit::new),
- updated_by: storage_scheme.to_string(),
- unified_code: Some(Some(unified_code)),
- unified_message: Some(unified_translated_message),
- connector_transaction_id: err.connector_transaction_id,
- payment_method_data: additional_payment_method_data,
- authentication_type: auth_update,
- issuer_error_code: err.network_decline_code,
- issuer_error_message: err.network_error_message,
- }),
- )
- }
- };
- (capture_update, attempt_update)
+ };
+ (
+ None,
+ Some(storage::PaymentAttemptUpdate::ErrorUpdate {
+ connector: None,
+ status,
+ error_message: Some(Some(err.message)),
+ error_code: Some(Some(err.code)),
+ error_reason: Some(err.reason),
+ amount_capturable: router_data
+ .request
+ .get_amount_capturable(&payment_data, status)
+ .map(MinorUnit::new),
+ updated_by: storage_scheme.to_string(),
+ unified_code: Some(Some(unified_code)),
+ unified_message: Some(unified_translated_message),
+ connector_transaction_id: err.connector_transaction_id,
+ payment_method_data: additional_payment_method_data,
+ authentication_type: auth_update,
+ issuer_error_code: err.network_decline_code,
+ issuer_error_message: err.network_error_message,
+ }),
+ option_gsm.and_then(|option_gsm| option_gsm.error_category),
+ )
+ }
+ };
+ (capture_update, attempt_update, gsm_error_category)
}
Ok(payments_response) => {
@@ -1572,6 +1582,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
issuer_error_code: None,
issuer_error_message: None,
}),
+ None,
)
}
Ok(()) => {
@@ -1627,7 +1638,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
updated_by: storage_scheme.to_string(),
};
- (None, Some(payment_attempt_update))
+ (None, Some(payment_attempt_update), None)
}
types::PaymentsResponseData::TransactionResponse {
resource_id,
@@ -1845,7 +1856,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
),
};
- (capture_updates, payment_attempt_update)
+ (capture_updates, payment_attempt_update, None)
}
types::PaymentsResponseData::TransactionUnresolvedResponse {
resource_id,
@@ -1873,23 +1884,30 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
}),
+ None,
)
}
- types::PaymentsResponseData::SessionResponse { .. } => (None, None),
- types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
- types::PaymentsResponseData::TokenizationResponse { .. } => (None, None),
+ types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),
+ types::PaymentsResponseData::SessionTokenResponse { .. } => {
+ (None, None, None)
+ }
+ types::PaymentsResponseData::TokenizationResponse { .. } => {
+ (None, None, None)
+ }
types::PaymentsResponseData::ConnectorCustomerResponse { .. } => {
- (None, None)
+ (None, None, None)
}
types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {
- (None, None)
+ (None, None, None)
+ }
+ types::PaymentsResponseData::PostProcessingResponse { .. } => {
+ (None, None, None)
}
- types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None),
types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
- } => (None, None),
+ } => (None, None, None),
types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => {
- (None, None)
+ (None, None, None)
}
types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
@@ -1899,9 +1917,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
&multiple_capture_data,
capture_sync_response_list,
)?;
- (Some((multiple_capture_data, capture_update_list)), None)
+ (
+ Some((multiple_capture_data, capture_update_list)),
+ None,
+ None,
+ )
}
- None => (None, None),
+ None => (None, None, None),
},
}
}
@@ -2139,6 +2161,23 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.map_err(|e| logger::error!(success_based_routing_metrics_error=?e))
.ok();
+ if let Some(gsm_error_category) = gsm_error_category {
+ if gsm_error_category.should_perform_elimination_routing() {
+ logger::info!("Performing update window for elimination routing");
+ routing_helpers::update_window_for_elimination_routing(
+ &state,
+ &payment_attempt,
+ &profile_id,
+ dynamic_routing_algo_ref.clone(),
+ dynamic_routing_config_params_interpolator.clone(),
+ gsm_error_category,
+ )
+ .await
+ .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
+ .ok();
+ };
+ };
+
routing_helpers::push_metrics_with_update_window_for_contract_based_routing(
&state,
&payment_attempt,
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 889525ec6d5..4e3e24c83f3 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -26,6 +26,7 @@ use euclid::{
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
+ elimination_based_client::{EliminationBasedRouting, EliminationResponse},
success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting},
DynamicRoutingError,
};
@@ -1510,7 +1511,7 @@ pub async fn perform_dynamic_routing(
profile.get_id().get_string_repr()
);
- let connector_list = match dynamic_routing_algo_ref
+ let mut connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
.as_ref()
.async_map(|algorithm| {
@@ -1539,7 +1540,7 @@ pub async fn perform_dynamic_routing(
state,
routable_connectors.clone(),
profile.get_id(),
- dynamic_routing_config_params_interpolator,
+ dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
)
})
@@ -1548,10 +1549,29 @@ pub async fn perform_dynamic_routing(
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
- .unwrap_or(routable_connectors)
+ .unwrap_or(routable_connectors.clone())
}
};
+ connector_list = dynamic_routing_algo_ref
+ .elimination_routing_algorithm
+ .as_ref()
+ .async_map(|algorithm| {
+ perform_elimination_routing(
+ state,
+ connector_list.clone(),
+ profile.get_id(),
+ dynamic_routing_config_params_interpolator.clone(),
+ algorithm.clone(),
+ )
+ })
+ .await
+ .transpose()
+ .inspect_err(|e| logger::error!(dynamic_routing_error=?e))
+ .ok()
+ .flatten()
+ .unwrap_or(connector_list);
+
Ok(connector_list)
}
@@ -1654,6 +1674,127 @@ pub async fn perform_success_based_routing(
}
}
+/// elimination dynamic routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn perform_elimination_routing(
+ state: &SessionState,
+ routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
+ profile_id: &common_utils::id_type::ProfileId,
+ elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
+ elimination_algo_ref: api_routing::EliminationRoutingAlgorithm,
+) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
+ if elimination_algo_ref.enabled_feature
+ == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
+ {
+ logger::debug!(
+ "performing elimination_routing for profile {}",
+ profile_id.get_string_repr()
+ );
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .elimination_based_client
+ .as_ref()
+ .ok_or(errors::RoutingError::EliminationClientInitializationError)
+ .attach_printable("elimination routing's gRPC client not found")?;
+
+ let elimination_routing_config = routing::helpers::fetch_dynamic_routing_configs::<
+ api_routing::EliminationRoutingConfig,
+ >(
+ state,
+ profile_id,
+ elimination_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::RoutingError::GenericNotFoundError {
+ field: "elimination_routing_algorithm_id".to_string(),
+ })
+ .attach_printable(
+ "elimination_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::RoutingError::EliminationRoutingConfigError)
+ .attach_printable("unable to fetch elimination dynamic routing configs")?;
+
+ let elimination_routing_config_params = elimination_routing_configs_params_interpolator
+ .get_string_val(
+ elimination_routing_config
+ .params
+ .as_ref()
+ .ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?,
+ );
+
+ let elimination_based_connectors: EliminationResponse = client
+ .perform_elimination_routing(
+ profile_id.get_string_repr().to_string(),
+ elimination_routing_config_params,
+ routable_connectors.clone(),
+ elimination_routing_config.elimination_analyser_config,
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::RoutingError::EliminationRoutingCalculationError)
+ .attach_printable(
+ "unable to analyze/fetch elimination routing from dynamic routing service",
+ )?;
+ let mut connectors =
+ Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
+ let mut eliminated_connectors =
+ Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
+ let mut non_eliminated_connectors =
+ Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
+ for labels_with_status in elimination_based_connectors.labels_with_status {
+ let (connector, merchant_connector_id) = labels_with_status.label
+ .split_once(':')
+ .ok_or(errors::RoutingError::InvalidEliminationBasedConnectorLabel(labels_with_status.label.to_string()))
+ .attach_printable(
+ "unable to split connector_name and mca_id from the label obtained by the elimination based dynamic routing service",
+ )?;
+
+ let routable_connector = api_routing::RoutableConnectorChoice {
+ choice_kind: api_routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(connector)
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "RoutableConnectors".to_string(),
+ })
+ .attach_printable("unable to convert String to RoutableConnectors")?,
+ merchant_connector_id: Some(
+ common_utils::id_type::MerchantConnectorAccountId::wrap(
+ merchant_connector_id.to_string(),
+ )
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "MerchantConnectorAccountId".to_string(),
+ })
+ .attach_printable("unable to convert MerchantConnectorAccountId from string")?,
+ ),
+ };
+
+ if labels_with_status
+ .elimination_information
+ .is_some_and(|elimination_info| {
+ elimination_info
+ .entity
+ .is_some_and(|entity_info| entity_info.is_eliminated)
+ })
+ {
+ eliminated_connectors.push(routable_connector);
+ } else {
+ non_eliminated_connectors.push(routable_connector);
+ }
+ connectors.extend(non_eliminated_connectors.clone());
+ connectors.extend(eliminated_connectors.clone());
+ }
+ logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors);
+ logger::debug!(dynamic_elimination_based_routing_connectors=?connectors);
+ Ok(connectors)
+ } else {
+ Ok(routable_connectors)
+ }
+}
+
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_contract_based_routing(
state: &SessionState,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index ec86102eba0..5caffd7e763 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -21,9 +21,10 @@ use error_stack::ResultExt;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
+ elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
-#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use router_env::logger;
@@ -607,6 +608,43 @@ impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
}
}
+#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+#[async_trait::async_trait]
+impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
+ async fn get_cached_dynamic_routing_config_for_profile(
+ state: &SessionState,
+ key: &str,
+ ) -> Option<Arc<Self>> {
+ cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+ .get_val::<Arc<Self>>(cache::CacheKey {
+ key: key.to_string(),
+ prefix: state.tenant.redis_key_prefix.clone(),
+ })
+ .await
+ }
+
+ async fn refresh_dynamic_routing_cache<T, F, Fut>(
+ state: &SessionState,
+ key: &str,
+ func: F,
+ ) -> RouterResult<T>
+ where
+ F: FnOnce() -> Fut + Send,
+ T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
+ Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
+ {
+ cache::get_or_populate_in_memory(
+ state.store.get_cache_store().as_ref(),
+ key,
+ func,
+ &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to populate ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE")
+ }
+}
+
/// Cfetch dynamic routing configs
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
@@ -941,6 +979,99 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
}
}
+/// update window for elimination based dynamic routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+#[instrument(skip_all)]
+pub async fn update_window_for_elimination_routing(
+ state: &SessionState,
+ payment_attempt: &storage::PaymentAttempt,
+ profile_id: &id_type::ProfileId,
+ dynamic_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
+ elimination_routing_configs_params_interpolator: DynamicRoutingConfigParamsInterpolator,
+ gsm_error_category: common_enums::ErrorCategory,
+) -> RouterResult<()> {
+ if let Some(elimination_algo_ref) = dynamic_algo_ref.elimination_routing_algorithm {
+ if elimination_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .elimination_based_client
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "elimination_rate gRPC client not found".to_string(),
+ })?;
+
+ let elimination_routing_config = fetch_dynamic_routing_configs::<
+ routing_types::EliminationRoutingConfig,
+ >(
+ state,
+ profile_id,
+ elimination_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "elimination routing algorithm_id not found".to_string(),
+ })
+ .attach_printable(
+ "elimination_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "elimination based dynamic routing configs not found".to_string(),
+ })
+ .attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
+
+ let payment_connector = &payment_attempt.connector.clone().ok_or(
+ errors::ApiErrorResponse::GenericNotFoundError {
+ message: "unable to derive payment connector from payment attempt".to_string(),
+ },
+ )?;
+
+ let elimination_routing_config_params = elimination_routing_configs_params_interpolator
+ .get_string_val(
+ elimination_routing_config
+ .params
+ .as_ref()
+ .ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ );
+
+ client
+ .update_elimination_bucket_config(
+ profile_id.get_string_repr().to_string(),
+ elimination_routing_config_params,
+ vec![routing_types::RoutableConnectorChoiceWithBucketName::new(
+ routing_types::RoutableConnectorChoice {
+ choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(
+ payment_connector.as_str(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to infer routable_connector from connector",
+ )?,
+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ },
+ gsm_error_category.to_string(),
+ )],
+ elimination_routing_config.elimination_analyser_config,
+ state.get_grpc_headers(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to update elimination based routing buckets in dynamic routing service",
+ )?;
+ Ok(())
+ } else {
+ Ok(())
+ }
+ } else {
+ Ok(())
+ }
+}
+
/// metrics for contract based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
|
2024-12-12T04:52:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will integrate elimination routing in our core flows for connectors to be filtered on basis of error codes received.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Testing performed in same way as SR routing.
1. Enable ER for merchant
```
curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/elimination/toggle?enable=dynamic_connector_selection' \
--header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f'
```
2. Enable Volume split
```
curl --location --request POST 'http://localhost:8080/account/merchant_1744368166/business_profile/pro_GrzjTHd5Pn5hAhwTZPRn/dynamic_routing/set_volume_split?split=100' \
--header 'api-key: dev_a4XMpNXd3Yriz5DPsiwU6UbxEkiRkXdqHhwnJPolnVhssLaDEbOg6f5kE6B2hx1f'
```
3. Create a volte Payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_lnvARj6hcC6DXOC3XXByk5s2qv7EWGhG0v9vFo85RQvz3Ft9IrqMXeSMpvuotZfp' \
--data-raw '{
"amount": 8000,
"currency": "EUR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 8000,
"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://www.google.com/",
"payment_method": "bank_redirect",
"payment_method_type": "open_banking_uk",
"payment_method_data": {
"bank_redirect": {
"open_banking_uk": {}
}
},
"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": "DE",
"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_KEc20awDxPq8pSIDsBV0"
}'
```
cancel the payment after going to the payment url.
4. logs checkup:
`DEBUG router::core::payments::routing: dynamic_eliminated_connectors: []`
if the above log is present, it shows elimination is working fine.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2a4670537a5c0e40e70d2afec0a2ba6124f03927
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6585
|
Bug: [REFACTOR] Move cybersource, bankofamerica, wellsfargo to crate hyperswitch_connectors
### Feature Description
Move cybersource, bankofamerica, wellsfargo code to crate hyperswitch_connectors.
### Possible Implementation
Move cybersource, bankofamerica, wellsfargo code to 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 2007f4f88a0..7583fb2eeee 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4003,6 +4003,7 @@ dependencies = [
"hyperswitch_domain_models",
"hyperswitch_interfaces",
"image",
+ "josekit",
"lazy_static",
"masking",
"mime",
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index ca9e77283cd..68ea60af8c6 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -21,6 +21,7 @@ error-stack = "0.4.1"
hex = "0.4.3"
http = "0.2.12"
image = { version = "0.25.1", default-features = false, features = ["png"] }
+josekit = "0.8.6"
mime = "0.3.17"
once_cell = "1.19.0"
qrcode = "0.14.0"
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index d5a695fe01d..bd646c95eb9 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -2,6 +2,7 @@ pub mod airwallex;
pub mod amazonpay;
pub mod bambora;
pub mod bamboraapac;
+pub mod bankofamerica;
pub mod billwerk;
pub mod bitpay;
pub mod bluesnap;
@@ -10,6 +11,7 @@ pub mod cashtocode;
pub mod coinbase;
pub mod cryptopay;
pub mod ctp_mastercard;
+pub mod cybersource;
pub mod datatrans;
pub mod deutschebank;
pub mod digitalvirgo;
@@ -47,6 +49,7 @@ pub mod thunes;
pub mod tsys;
pub mod unified_authentication_service;
pub mod volt;
+pub mod wellsfargo;
pub mod worldline;
pub mod worldpay;
pub mod xendit;
@@ -55,8 +58,9 @@ pub mod zsl;
pub use self::{
airwallex::Airwallex, amazonpay::Amazonpay, bambora::Bambora, bamboraapac::Bamboraapac,
- billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, cashtocode::Cashtocode,
- coinbase::Coinbase, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, datatrans::Datatrans,
+ bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap,
+ boku::Boku, cashtocode::Cashtocode, coinbase::Coinbase, cryptopay::Cryptopay,
+ ctp_mastercard::CtpMastercard, cybersource::Cybersource, datatrans::Datatrans,
deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon,
fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, globepay::Globepay,
gocardless::Gocardless, helcim::Helcim, inespay::Inespay, jpmorgan::Jpmorgan, mollie::Mollie,
@@ -65,5 +69,6 @@ pub use self::{
powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay,
redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes,
tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt,
- worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl,
+ wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen,
+ zsl::Zsl,
};
diff --git a/crates/router/src/connector/bankofamerica.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
similarity index 70%
rename from crates/router/src/connector/bankofamerica.rs
rename to crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
index 95ceee55589..36d12fe3fc5 100644
--- a/crates/router/src/connector/bankofamerica.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
@@ -3,36 +3,57 @@ pub mod transformers;
use std::fmt::Debug;
use base64::Engine;
-use common_utils::request::RequestContent;
-use diesel_models::enums;
+use common_enums::enums;
+use common_utils::{
+ consts,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::{report, ResultExt};
-use masking::{ExposeInterface, PeekInterface};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ 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,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
+ RefundExecuteType, RefundSyncType, Response, SetupMandateType,
+ },
+ webhooks,
+};
+use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as bankofamerica;
use url::Url;
use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{PaymentMethodDataType, RefundsRequestData},
- },
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
- },
- utils::BytesExt,
+ constants::{self, headers},
+ types::ResponseRouterData,
+ utils::{self, PaymentMethodDataType, RefundsRequestData},
};
pub const V_C_MERCHANT_ID: &str = "v-c-merchant-id";
@@ -66,14 +87,14 @@ impl Bankofamerica {
resource: &str,
payload: &String,
date: OffsetDateTime,
- http_method: services::Method,
+ http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let bankofamerica::BankOfAmericaAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
- let is_post_method = matches!(http_method, services::Method::Post);
+ let is_post_method = matches!(http_method, Method::Post);
let digest_str = if is_post_method { "digest " } else { "" };
let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}");
let request_target = if is_post_method {
@@ -102,12 +123,8 @@ impl Bankofamerica {
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Bankofamerica
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Bankofamerica
{
// Not Implemented (R)
}
@@ -118,9 +135,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 date = OffsetDateTime::now_utc();
let boa_req = self.get_request_body(req, connectors)?;
let http_method = self.get_http_method();
@@ -161,7 +178,7 @@ where
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
- if matches!(http_method, services::Method::Post | services::Method::Put) {
+ if matches!(http_method, Method::Post | Method::Put) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
@@ -184,7 +201,7 @@ impl ConnectorCommon for Bankofamerica {
"application/json;charset=utf-8"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.bankofamerica.base_url.as_ref()
}
@@ -202,9 +219,9 @@ impl ConnectorCommon for Bankofamerica {
router_env::logger::info!(connector_response=?response);
let error_message = if res.status_code == 401 {
- consts::CONNECTOR_UNAUTHORIZED_ERROR
+ constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
- consts::NO_ERROR_MESSAGE
+ hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
transformers::BankOfAmericaErrorResponse::StandardError(response) => {
@@ -236,12 +253,10 @@ impl ConnectorCommon for Bankofamerica {
.join(", ")
});
(
- response
- .reason
- .clone()
- .map_or(consts::NO_ERROR_CODE.to_string(), |reason| {
- reason.to_string()
- }),
+ response.reason.clone().map_or(
+ hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
+ |reason| reason.to_string(),
+ ),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
@@ -266,7 +281,7 @@ impl ConnectorCommon for Bankofamerica {
transformers::BankOfAmericaErrorResponse::AuthenticationError(response) => {
Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
@@ -290,48 +305,39 @@ impl ConnectorValidation for Bankofamerica {
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
- connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bankofamerica {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Bankofamerica
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bankofamerica {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Bankofamerica
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Bankofamerica
{
fn get_headers(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -339,15 +345,15 @@ impl
}
fn get_url(
&self,
- _req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
+ _req: &SetupMandateRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::SetupMandateRouterData,
- _connectors: &settings::Connectors,
+ req: &SetupMandateRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bankofamerica::BankOfAmericaPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -355,31 +361,25 @@ impl
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> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::SetupMandateType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
- .set_body(types::SetupMandateType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::SetupMandateRouterData,
+ data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
+ ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaSetupMandatesResponse = res
.response
.parse_struct("BankOfAmericaSetupMandatesResponse")
@@ -388,7 +388,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,
@@ -426,24 +426,26 @@ impl
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Bankofamerica
{
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)
}
@@ -453,8 +455,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!(
"{}pts/v2/payments/",
@@ -464,8 +466,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 = bankofamerica::BankOfAmericaRouterData::try_from((
&self.get_currency_unit(),
@@ -480,20 +482,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(),
@@ -502,17 +500,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: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("Bankofamerica PaymentResponse")
.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,
@@ -550,24 +548,24 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Bankofamerica {
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)
}
@@ -575,14 +573,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 connector_payment_id = req
.request
@@ -597,32 +595,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: bankofamerica::BankOfAmericaTransactionResponse = res
.response
.parse_struct("BankOfAmerica PaymentSyncResponse")
.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,
@@ -638,14 +636,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bankofamerica {
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)
}
@@ -655,8 +651,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!(
@@ -667,8 +663,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_router_data = bankofamerica::BankOfAmericaRouterData::try_from((
&self.get_currency_unit(),
@@ -683,18 +679,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(),
@@ -703,17 +697,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> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("BankOfAmerica PaymentResponse")
.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,
@@ -744,31 +738,31 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Bankofamerica {
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)
}
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!(
@@ -783,8 +777,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_router_data = bankofamerica::BankOfAmericaRouterData::try_from((
&self.get_currency_unit(),
@@ -808,35 +802,33 @@ 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)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .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: bankofamerica::BankOfAmericaPaymentsResponse = res
.response
.parse_struct("BankOfAmerica PaymentResponse")
.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,
@@ -867,24 +859,24 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bankofamerica {
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)
}
@@ -894,8 +886,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!(
@@ -906,8 +898,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 = bankofamerica::BankOfAmericaRouterData::try_from((
&self.get_currency_unit(),
@@ -922,29 +914,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: bankofamerica::BankOfAmericaRefundResponse = res
.response
.parse_struct("bankofamerica RefundResponse")
@@ -953,7 +941,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,
@@ -969,14 +957,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Bankofamerica
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Bankofamerica {
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)
}
@@ -984,14 +970,14 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
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::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
@@ -1002,32 +988,32 @@ 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: bankofamerica::BankOfAmericaRsyncResponse = res
.response
.parse_struct("bankofamerica 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,
@@ -1044,24 +1030,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Bankofamerica {
+impl webhooks::IncomingWebhook for Bankofamerica {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _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> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ 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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
similarity index 70%
rename from crates/router/src/connector/bankofamerica/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
index 48363481ad8..3602f771928 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
@@ -1,38 +1,48 @@
use base64::Engine;
-use common_utils::pii;
+use common_enums::{enums, FutureUsage};
+use common_utils::{consts, pii};
+use hyperswitch_domain_models::{
+ payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData},
+ router_data::{
+ AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
+ ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData,
+ },
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::{
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData,
+ ResponseId,
+ },
+ router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ RefundsRouterData, SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
- connector::utils::{
- self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer,
- PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData,
- RecurringMandateData, RouterData,
- },
- consts,
- core::errors,
- types::{
- self,
- api::{self, enums as api_enums},
- domain,
- storage::enums,
- transformers::ForeignFrom,
- ApplePayPredecryptData,
- },
+ constants,
+ types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
+ utils::{
+ self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData,
+ PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData,
+ RouterData as OtherRouterData,
+ },
};
-
pub struct BankOfAmericaAuthType {
pub(super) api_key: Secret<String>,
pub(super) merchant_account: Secret<String>,
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for BankOfAmericaAuthType {
+impl TryFrom<&ConnectorAuthType> for BankOfAmericaAuthType {
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,
@@ -54,10 +64,17 @@ pub struct BankOfAmericaRouterData<T> {
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BankOfAmericaRouterData<T> {
+impl<T> TryFrom<(&api::CurrencyUnit, api_models::enums::Currency, i64, T)>
+ for BankOfAmericaRouterData<T>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
+ (currency_unit, currency, amount, item): (
+ &api::CurrencyUnit,
+ api_models::enums::Currency,
+ i64,
+ T,
+ ),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
Ok(Self {
@@ -264,68 +281,64 @@ pub struct BillTo {
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
- country: Option<api_enums::CountryAlpha2>,
+ country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
-impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
+impl TryFrom<&SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
- Self::try_from((item, apple_pay_data))
- }
- domain::WalletData::GooglePay(google_pay_data) => {
- Self::try_from((item, google_pay_data))
- }
- 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::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(
+ PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)),
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => Self::try_from((item, apple_pay_data)),
+ WalletData::GooglePay(google_pay_data) => Self::try_from((item, google_pay_data)),
+ 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::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("BankOfAmerica"),
))?,
},
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("BankOfAmerica"),
))?
@@ -335,38 +348,29 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest {
}
impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- BankOfAmericaSetupMandatesResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ TryFrom<ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- BankOfAmericaSetupMandatesResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, BankOfAmericaSetupMandatesResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaSetupMandatesResponse::ClientReferenceInformation(info_response) => {
- let mandate_reference = info_response.token_information.clone().map(|token_info| {
- types::MandateReference {
- connector_mandate_id: token_info
- .payment_instrument
- .map(|payment_instrument| payment_instrument.id.expose()),
- payment_method_id: None,
- mandate_metadata: None,
- connector_mandate_request_reference_id: None,
- }
- });
+ let mandate_reference =
+ info_response
+ .token_information
+ .clone()
+ .map(|token_info| MandateReference {
+ connector_mandate_id: token_info
+ .payment_instrument
+ .map(|payment_instrument| payment_instrument.id.expose()),
+ payment_method_id: None,
+ mandate_metadata: None,
+ connector_mandate_request_reference_id: None,
+ });
let mut mandate_status =
- enums::AttemptStatus::foreign_from((info_response.status.clone(), false));
+ map_boa_attempt_status((info_response.status.clone(), false));
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
@@ -383,13 +387,13 @@ impl<F, T>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::foreign_from((
+ convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
- ))
+ )
})
})
- .map(types::ConnectorResponseData::with_additional_payment_method_data),
+ .map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
@@ -410,8 +414,8 @@ impl<F, T>
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
- None => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ None => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
info_response.id.clone(),
),
redirection_data: Box::new(None),
@@ -434,10 +438,10 @@ impl<F, T>
})
}
BankOfAmericaSetupMandatesResponse::ErrorInformation(error_response) => {
- let response = Err(types::ErrorResponse::foreign_from((
- &*error_response,
+ let response = Err(convert_to_error_response_from_error_info(
+ &error_response,
item.http_code,
- )));
+ ));
Ok(Self {
response,
status: enums::AttemptStatus::Failure,
@@ -522,23 +526,6 @@ fn build_bill_to(
.unwrap_or(default_address))
}
-impl From<CardIssuer> for String {
- fn from(card_issuer: CardIssuer) -> Self {
- let card_type = match card_issuer {
- CardIssuer::AmericanExpress => "003",
- CardIssuer::Master => "002",
- //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
- CardIssuer::Maestro => "042",
- CardIssuer::Visa => "001",
- CardIssuer::Discover => "004",
- CardIssuer::DinersClub => "005",
- CardIssuer::CarteBlanche => "006",
- CardIssuer::JCB => "007",
- };
- card_type.to_string()
- }
-}
-
fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static str> {
match card_network {
common_enums::CardNetwork::Visa => Some("001"),
@@ -579,13 +566,13 @@ pub enum TransactionType {
impl
From<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
@@ -601,7 +588,7 @@ impl
impl
TryFrom<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
@@ -610,52 +597,51 @@ impl
fn try_from(
(item, solution, network): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
) -> Result<Self, Self::Error> {
- let (action_list, action_token_types, authorization_options) = if item
- .router_data
- .request
- .setup_future_usage
- == Some(common_enums::FutureUsage::OffSession)
- && (item.router_data.request.customer_acceptance.is_some()
- || item
+ let (action_list, action_token_types, authorization_options) =
+ if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession)
+ && (item.router_data.request.customer_acceptance.is_some()
+ || item
+ .router_data
+ .request
+ .setup_mandate_details
+ .clone()
+ .is_some_and(|mandate_details| {
+ mandate_details.customer_acceptance.is_some()
+ }))
+ {
+ get_boa_mandate_action_details()
+ } else if item.router_data.request.connector_mandate_id().is_some() {
+ let original_amount = item
.router_data
- .request
- .setup_mandate_details
- .clone()
- .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some()))
- {
- get_boa_mandate_action_details()
- } else if item.router_data.request.connector_mandate_id().is_some() {
- let original_amount = item
- .router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_amount()?;
- let original_currency = item
- .router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_currency()?;
- (
- None,
- None,
- Some(BankOfAmericaAuthorizationOptions {
- initiator: None,
- merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
- reason: None,
- original_authorized_amount: Some(utils::get_amount_as_string(
- &api::CurrencyUnit::Base,
- original_amount,
- original_currency,
- )?),
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_amount()?;
+ let original_currency = item
+ .router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_currency()?;
+ (
+ None,
+ None,
+ Some(BankOfAmericaAuthorizationOptions {
+ initiator: None,
+ merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
+ reason: None,
+ original_authorized_amount: Some(utils::get_amount_as_string(
+ &api::CurrencyUnit::Base,
+ original_amount,
+ original_currency,
+ )?),
+ }),
}),
- }),
- )
- } else {
- (None, None, None)
- };
+ )
+ } else {
+ (None, None, None)
+ };
let commerce_indicator = get_commerce_indicator(network);
@@ -674,40 +660,35 @@ impl
}
}
-impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
- for ClientReferenceInformation
-{
- fn from(item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+impl From<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
+ fn from(item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
-impl From<&types::SetupMandateRouterData> for ClientReferenceInformation {
- fn from(item: &types::SetupMandateRouterData) -> Self {
+impl From<&SetupMandateRouterData> for ClientReferenceInformation {
+ fn from(item: &SetupMandateRouterData) -> Self {
Self {
code: Some(item.connector_request_reference_id.clone()),
}
}
}
-impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> {
- fn foreign_from(metadata: Value) -> Self {
- let hashmap: std::collections::BTreeMap<String, Value> =
- serde_json::from_str(&metadata.to_string())
- .unwrap_or(std::collections::BTreeMap::new());
- let mut vector: Self = Self::new();
- let mut iter = 1;
- for (key, value) in hashmap {
- vector.push(MerchantDefinedInformation {
- key: iter,
- value: format!("{key}={value}"),
- });
- iter += 1;
- }
- vector
+fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
+ let hashmap: std::collections::BTreeMap<String, Value> =
+ serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
+ let mut vector = Vec::new();
+ let mut iter = 1;
+ for (key, value) in hashmap {
+ vector.push(MerchantDefinedInformation {
+ key: iter,
+ value: format!("{key}={value}"),
+ });
+ iter += 1;
}
+ vector
}
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -821,15 +802,15 @@ pub struct Avs {
impl
TryFrom<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -843,7 +824,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -858,17 +839,17 @@ impl
impl
TryFrom<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -886,7 +867,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
@@ -916,15 +897,15 @@ impl
impl
TryFrom<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -939,7 +920,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -952,33 +933,33 @@ impl
}
}
-impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
+impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>>
for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.connector_mandate_id() {
Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)),
None => {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
+ PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
- types::PaymentMethodToken::Token(_) => {
+ PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?
}
- types::PaymentMethodToken::PazeDecrypt(_) => Err(
+ PaymentMethodToken::PazeDecrypt(_) => Err(
unimplemented_payment_method!("Paze", "Bank Of America"),
)?,
},
@@ -1000,12 +981,12 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
ClientReferenceInformation::from(item);
let payment_information =
PaymentInformation::from(&apple_pay_data);
- let merchant_defined_information =
- item.router_data.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(
- metadata,
- )
- });
+ let merchant_defined_information = item
+ .router_data
+ .request
+ .metadata
+ .clone()
+ .map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_data
.payment_method
.network
@@ -1035,47 +1016,45 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
}
- domain::WalletData::GooglePay(google_pay_data) => {
+ WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
- 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::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(
- utils::get_unimplemented_payment_method_error_message(
- "Bank of America",
- ),
- )
- .into())
- }
+ 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::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(
+ "Bank of America",
+ ),
+ )
+ .into()),
},
// If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause.
// This is a fallback implementation in the event of catastrophe.
- domain::PaymentMethodData::MandatePayment => {
+ PaymentMethodData::MandatePayment => {
let connector_mandate_id =
item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -1084,22 +1063,22 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
)?;
Self::try_from((item, connector_mandate_id))
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | 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(
"Bank of America",
@@ -1115,14 +1094,14 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
impl
TryFrom<(
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
- &BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
+ &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
@@ -1145,7 +1124,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
@@ -1181,42 +1160,44 @@ pub enum BankofamericaPaymentStatus {
//PartialAuthorized, not being consumed yet.
}
-impl ForeignFrom<(BankofamericaPaymentStatus, bool)> for enums::AttemptStatus {
- fn foreign_from((status, auto_capture): (BankofamericaPaymentStatus, bool)) -> Self {
- match status {
- BankofamericaPaymentStatus::Authorized
- | BankofamericaPaymentStatus::AuthorizedPendingReview => {
- if auto_capture {
- // Because BankOfAmerica will return Payment Status as Authorized even in AutoCapture Payment
- Self::Charged
- } else {
- Self::Authorized
- }
- }
- BankofamericaPaymentStatus::Pending => {
- if auto_capture {
- Self::Charged
- } else {
- Self::Pending
- }
+fn map_boa_attempt_status(
+ (status, auto_capture): (BankofamericaPaymentStatus, bool),
+) -> enums::AttemptStatus {
+ match status {
+ BankofamericaPaymentStatus::Authorized
+ | BankofamericaPaymentStatus::AuthorizedPendingReview => {
+ if auto_capture {
+ // Because BankOfAmerica will return Payment Status as Authorized even in AutoCapture Payment
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Authorized
}
- BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => {
- Self::Charged
+ }
+ BankofamericaPaymentStatus::Pending => {
+ if auto_capture {
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Pending
}
- BankofamericaPaymentStatus::Voided
- | BankofamericaPaymentStatus::Reversed
- | BankofamericaPaymentStatus::Cancelled => Self::Voided,
- BankofamericaPaymentStatus::Failed
- | BankofamericaPaymentStatus::Declined
- | BankofamericaPaymentStatus::AuthorizedRiskDeclined
- | BankofamericaPaymentStatus::InvalidRequest
- | BankofamericaPaymentStatus::Rejected
- | BankofamericaPaymentStatus::ServerError => Self::Failure,
- BankofamericaPaymentStatus::PendingAuthentication => Self::AuthenticationPending,
- BankofamericaPaymentStatus::PendingReview
- | BankofamericaPaymentStatus::Challenge
- | BankofamericaPaymentStatus::Accepted => Self::Pending,
}
+ BankofamericaPaymentStatus::Succeeded | BankofamericaPaymentStatus::Transmitted => {
+ enums::AttemptStatus::Charged
+ }
+ BankofamericaPaymentStatus::Voided
+ | BankofamericaPaymentStatus::Reversed
+ | BankofamericaPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
+ BankofamericaPaymentStatus::Failed
+ | BankofamericaPaymentStatus::Declined
+ | BankofamericaPaymentStatus::AuthorizedRiskDeclined
+ | BankofamericaPaymentStatus::InvalidRequest
+ | BankofamericaPaymentStatus::Rejected
+ | BankofamericaPaymentStatus::ServerError => enums::AttemptStatus::Failure,
+ BankofamericaPaymentStatus::PendingAuthentication => {
+ enums::AttemptStatus::AuthenticationPending
+ }
+ BankofamericaPaymentStatus::PendingReview
+ | BankofamericaPaymentStatus::Challenge
+ | BankofamericaPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
@@ -1300,7 +1281,7 @@ pub struct PaymentInformationResponse {
bin: Option<String>,
account_type: Option<String>,
issuer: Option<String>,
- bin_country: Option<api_enums::CountryAlpha2>,
+ bin_country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -1371,7 +1352,7 @@ pub struct BankOfAmericaTokenInformation {
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IssuerInformation {
- country: Option<api_enums::CountryAlpha2>,
+ country: Option<enums::CountryAlpha2>,
discretionary_data: Option<String>,
country_specific_discretionary_data: Option<String>,
response_code: Option<String>,
@@ -1403,71 +1384,55 @@ pub struct BankOfAmericaErrorInformation {
details: Option<Vec<Details>>,
}
-impl<F, T>
- ForeignFrom<(
- &BankOfAmericaErrorInformationResponse,
- types::ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, types::PaymentsResponseData>,
- Option<enums::AttemptStatus>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
-{
- fn foreign_from(
- (error_response, item, transaction_status): (
- &BankOfAmericaErrorInformationResponse,
- types::ResponseRouterData<
- F,
- BankOfAmericaPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
- Option<enums::AttemptStatus>,
- ),
- ) -> Self {
- let detailed_error_info =
- error_response
- .error_information
- .details
- .as_ref()
- .map(|details| {
- details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", ")
- });
-
- let reason = get_error_reason(
- error_response.error_information.message.clone(),
- detailed_error_info,
- None,
- );
- let response = Err(types::ErrorResponse {
- code: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code: item.http_code,
- attempt_status: None,
- connector_transaction_id: Some(error_response.id.clone()),
+fn map_error_response<F, T>(
+ error_response: &BankOfAmericaErrorInformationResponse,
+ item: ResponseRouterData<F, BankOfAmericaPaymentsResponse, T, PaymentsResponseData>,
+ transaction_status: Option<enums::AttemptStatus>,
+) -> RouterData<F, T, PaymentsResponseData> {
+ let detailed_error_info = error_response
+ .error_information
+ .details
+ .as_ref()
+ .map(|details| {
+ details
+ .iter()
+ .map(|details| format!("{} : {}", details.field, details.reason))
+ .collect::<Vec<_>>()
+ .join(", ")
});
- match transaction_status {
- Some(status) => Self {
- response,
- status,
- ..item.data
- },
- None => Self {
- response,
- ..item.data
- },
- }
+ let reason = get_error_reason(
+ error_response.error_information.message.clone(),
+ detailed_error_info,
+ None,
+ );
+ let response = Err(ErrorResponse {
+ code: error_response
+ .error_information
+ .reason
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_response
+ .error_information
+ .reason
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ reason,
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(error_response.id.clone()),
+ });
+
+ match transaction_status {
+ Some(status) => RouterData {
+ response,
+ status,
+ ..item.data
+ },
+ None => RouterData {
+ response,
+ ..item.data
+ },
}
}
@@ -1477,15 +1442,15 @@ fn get_error_response_if_failure(
enums::AttemptStatus,
u16,
),
-) -> Option<types::ErrorResponse> {
+) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
- Some(types::ErrorResponse::foreign_from((
+ Some(get_error_response(
&info_response.error_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
- )))
+ ))
} else {
None
}
@@ -1497,7 +1462,7 @@ fn get_payment_response(
enums::AttemptStatus,
u16,
),
-) -> Result<types::PaymentsResponseData, types::ErrorResponse> {
+) -> Result<PaymentsResponseData, ErrorResponse> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(error),
@@ -1506,7 +1471,7 @@ fn get_payment_response(
info_response
.token_information
.clone()
- .map(|token_info| types::MandateReference {
+ .map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
@@ -1515,8 +1480,8 @@ fn get_payment_response(
connector_mandate_request_reference_id: None,
});
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -1537,26 +1502,26 @@ fn get_payment_response(
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
- 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,
BankOfAmericaPaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_boa_attempt_status((
info_response.status.clone(),
item.data.request.is_auto_capture()?,
));
@@ -1570,13 +1535,13 @@ impl<F>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::foreign_from((
+ convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
- ))
+ )
})
})
- .map(types::ConnectorResponseData::with_additional_payment_method_data),
+ .map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
@@ -1601,31 +1566,21 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::foreign_from((
- &*error_response.clone(),
+ Ok(map_error_response(
+ &error_response.clone(),
item,
Some(enums::AttemptStatus::Failure),
- )))
+ ))
}
}
}
}
-impl
- ForeignFrom<(
- &ClientProcessorInformation,
- &ConsumerAuthenticationInformation,
- )> for types::AdditionalPaymentMethodConnectorResponse
-{
- fn foreign_from(
- item: (
- &ClientProcessorInformation,
- &ConsumerAuthenticationInformation,
- ),
- ) -> Self {
- let processor_information = item.0;
- let consumer_authentication_information = item.1;
- let payment_checks = Some(serde_json::json!({
+fn convert_to_additional_payment_method_connector_response(
+ processor_information: &ClientProcessorInformation,
+ consumer_authentication_information: &ConsumerAuthenticationInformation,
+) -> AdditionalPaymentMethodConnectorResponse {
+ let payment_checks = Some(serde_json::json!({
"avs_response": processor_information.avs,
"card_verification": processor_information.card_verification,
"approval_code": processor_information.approval_code,
@@ -1633,44 +1588,42 @@ impl
"cavv": consumer_authentication_information.cavv,
"eci": consumer_authentication_information.eci,
"eci_raw": consumer_authentication_information.eci_raw,
- }));
+ }));
- let authentication_data = Some(serde_json::json!({
+ let authentication_data = Some(serde_json::json!({
"retrieval_reference_number": processor_information.retrieval_reference_number,
"acs_transaction_id": consumer_authentication_information.acs_transaction_id,
"system_trace_audit_number": processor_information.system_trace_audit_number,
- }));
+ }));
- Self::Card {
- authentication_data,
- payment_checks,
- }
+ AdditionalPaymentMethodConnectorResponse::Card {
+ authentication_data,
+ payment_checks,
}
}
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
- let status =
- enums::AttemptStatus::foreign_from((info_response.status.clone(), true));
+ let status = map_boa_attempt_status((info_response.status.clone(), true));
let response = get_payment_response((&info_response, status, item.http_code));
Ok(Self {
status,
@@ -1679,7 +1632,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::foreign_from((&*error_response.clone(), item, None)))
+ Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
@@ -1687,27 +1640,26 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BankOfAmericaPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => {
- let status =
- enums::AttemptStatus::foreign_from((info_response.status.clone(), false));
+ let status = map_boa_attempt_status((info_response.status.clone(), false));
let response = get_payment_response((&info_response, status, item.http_code));
Ok(Self {
status,
@@ -1716,7 +1668,7 @@ impl<F>
})
}
BankOfAmericaPaymentsResponse::ErrorInformation(ref error_response) => {
- Ok(Self::foreign_from((&*error_response.clone(), item, None)))
+ Ok(map_error_response(&error_response.clone(), item, None))
}
}
}
@@ -1754,29 +1706,27 @@ pub struct ApplicationInformation {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
BankOfAmericaTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
BankOfAmericaTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(app_status) => {
- let status = enums::AttemptStatus::foreign_from((
- app_status,
- item.data.request.is_auto_capture()?,
- ));
+ let status =
+ map_boa_attempt_status((app_status, item.data.request.is_auto_capture()?));
let connector_response = match item.data.payment_method {
common_enums::PaymentMethod::Card => item
@@ -1788,13 +1738,13 @@ impl<F>
.consumer_authentication_information
.as_ref()
.map(|consumer_auth_information| {
- types::AdditionalPaymentMethodConnectorResponse::foreign_from((
+ convert_to_additional_payment_method_connector_response(
processor_information,
consumer_auth_information,
- ))
+ )
})
})
- .map(types::ConnectorResponseData::with_additional_payment_method_data),
+ .map(ConnectorResponseData::with_additional_payment_method_data),
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
@@ -1814,13 +1764,13 @@ impl<F>
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
- response: Err(types::ErrorResponse::foreign_from((
+ response: Err(get_error_response(
&item.response.error_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
- ))),
+ )),
status: enums::AttemptStatus::Failure,
connector_response,
..item.data
@@ -1828,8 +1778,8 @@ impl<F>
} else {
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
@@ -1851,10 +1801,8 @@ impl<F>
}
None => Ok(Self {
status: item.data.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: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -1884,19 +1832,17 @@ pub struct BankOfAmericaCaptureRequest {
merchant_defined_information: Option<Vec<MerchantDefinedInformation>>,
}
-impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>>
- for BankOfAmericaCaptureRequest
-{
+impl TryFrom<&BankOfAmericaRouterData<&PaymentsCaptureRouterData>> for BankOfAmericaCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: &BankOfAmericaRouterData<&types::PaymentsCaptureRouterData>,
+ value: &BankOfAmericaRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
@@ -1929,19 +1875,17 @@ pub struct ReversalInformation {
reason: String,
}
-impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsCancelRouterData>>
- for BankOfAmericaVoidRequest
-{
+impl TryFrom<&BankOfAmericaRouterData<&PaymentsCancelRouterData>> for BankOfAmericaVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: &BankOfAmericaRouterData<&types::PaymentsCancelRouterData>,
+ value: &BankOfAmericaRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
@@ -1976,12 +1920,10 @@ pub struct BankOfAmericaRefundRequest {
client_reference_information: ClientReferenceInformation,
}
-impl<F> TryFrom<&BankOfAmericaRouterData<&types::RefundsRouterData<F>>>
- for BankOfAmericaRefundRequest
-{
+impl<F> TryFrom<&BankOfAmericaRouterData<&RefundsRouterData<F>>> for BankOfAmericaRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &BankOfAmericaRouterData<&types::RefundsRouterData<F>>,
+ item: &BankOfAmericaRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
@@ -2029,24 +1971,24 @@ pub struct BankOfAmericaRefundResponse {
error_information: Option<BankOfAmericaErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, BankOfAmericaRefundResponse>,
+ item: RefundsResponseRouterData<Execute, BankOfAmericaRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.clone());
let response = if utils::is_refund_failure(refund_status) {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id,
- )))
+ ))
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
@@ -2086,12 +2028,12 @@ pub struct BankOfAmericaRsyncResponse {
error_information: Option<BankOfAmericaErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResponse>,
+ item: RefundsResponseRouterData<RSync, BankOfAmericaRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
@@ -2121,35 +2063,35 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, BankOfAmericaRsyncResp
};
if utils::is_refund_failure(refund_status) {
if status == BankofamericaRefundStatus::Voided {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&Some(BankOfAmericaErrorInformation {
- message: Some(consts::REFUND_VOIDED.to_string()),
- reason: Some(consts::REFUND_VOIDED.to_string()),
+ message: Some(constants::REFUND_VOIDED.to_string()),
+ reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
} else {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
}
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
- None => Ok(types::RefundsResponseData {
+ None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
@@ -2222,87 +2164,84 @@ pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
-impl
- ForeignFrom<(
- &Option<BankOfAmericaErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- )> for types::ErrorResponse
-{
- fn foreign_from(
- (error_data, risk_information, attempt_status, status_code, transaction_id): (
- &Option<BankOfAmericaErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- ),
- ) -> Self {
- let avs_message = risk_information
- .clone()
- .map(|client_risk_information| {
- client_risk_information.rules.map(|rules| {
- rules
- .iter()
- .map(|risk_info| {
- risk_info.name.clone().map_or("".to_string(), |name| {
- format!(" , {}", name.clone().expose())
- })
- })
- .collect::<Vec<String>>()
- .join("")
- })
- })
- .unwrap_or(Some("".to_string()));
-
- let detailed_error_info = error_data.to_owned().and_then(|error_info| {
- error_info.details.map(|error_details| {
- error_details
+fn get_error_response(
+ error_data: &Option<BankOfAmericaErrorInformation>,
+ risk_information: &Option<ClientRiskInformation>,
+ attempt_status: Option<enums::AttemptStatus>,
+ status_code: u16,
+ transaction_id: String,
+) -> ErrorResponse {
+ let avs_message = risk_information
+ .clone()
+ .map(|client_risk_information| {
+ client_risk_information.rules.map(|rules| {
+ rules
.iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", ")
+ .map(|risk_info| {
+ risk_info.name.clone().map_or("".to_string(), |name| {
+ format!(" , {}", name.clone().expose())
+ })
+ })
+ .collect::<Vec<String>>()
+ .join("")
})
- });
+ })
+ .unwrap_or(Some("".to_string()));
+
+ let detailed_error_info = error_data.to_owned().and_then(|error_info| {
+ error_info.details.map(|error_details| {
+ error_details
+ .iter()
+ .map(|details| format!("{} : {}", details.field, details.reason))
+ .collect::<Vec<_>>()
+ .join(", ")
+ })
+ });
- let reason = get_error_reason(
- error_data
- .clone()
- .and_then(|error_details| error_details.message),
- detailed_error_info,
- avs_message,
- );
- let error_message = error_data
+ let reason = get_error_reason(
+ error_data
.clone()
- .and_then(|error_details| error_details.reason);
-
- Self {
- code: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code,
- attempt_status,
- connector_transaction_id: Some(transaction_id.clone()),
- }
+ .and_then(|error_details| error_details.message),
+ detailed_error_info,
+ avs_message,
+ );
+ let error_message = error_data
+ .clone()
+ .and_then(|error_details| error_details.reason);
+
+ ErrorResponse {
+ code: error_message
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_message
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ reason,
+ status_code,
+ attempt_status,
+ connector_transaction_id: Some(transaction_id.clone()),
}
}
-impl TryFrom<(&types::SetupMandateRouterData, domain::Card)> for BankOfAmericaPaymentsRequest {
+impl
+ TryFrom<(
+ &SetupMandateRouterData,
+ hyperswitch_domain_models::payment_method_data::Card,
+ )> for BankOfAmericaPaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, ccard): (&types::SetupMandateRouterData, domain::Card),
+ (item, ccard): (
+ &SetupMandateRouterData,
+ hyperswitch_domain_models::payment_method_data::Card,
+ ),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
- let merchant_defined_information = item.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned())
- });
+ let merchant_defined_information =
+ item.request.metadata.clone().map(|metadata| {
+ convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
+ });
let payment_information = PaymentInformation::try_from(&ccard)?;
let processing_information = ProcessingInformation::try_from((None, None))?;
Ok(Self {
@@ -2316,29 +2255,28 @@ impl TryFrom<(&types::SetupMandateRouterData, domain::Card)> for BankOfAmericaPa
}
}
-impl TryFrom<(&types::SetupMandateRouterData, domain::ApplePayWalletData)>
- for BankOfAmericaPaymentsRequest
-{
+impl TryFrom<(&SetupMandateRouterData, ApplePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, apple_pay_data): (&types::SetupMandateRouterData, domain::ApplePayWalletData),
+ (item, apple_pay_data): (&SetupMandateRouterData, ApplePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
- let merchant_defined_information = item.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned())
- });
+ let merchant_defined_information =
+ item.request.metadata.clone().map(|metadata| {
+ convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
+ });
let payment_information = match item.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
PaymentInformation::try_from(&decrypt_data)?
}
- types::PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
+ PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Bank Of America"
))?,
- types::PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Bank Of America"))?
}
},
@@ -2377,18 +2315,17 @@ impl TryFrom<(&types::SetupMandateRouterData, domain::ApplePayWalletData)>
}
}
-impl TryFrom<(&types::SetupMandateRouterData, domain::GooglePayWalletData)>
- for BankOfAmericaPaymentsRequest
-{
+impl TryFrom<(&SetupMandateRouterData, GooglePayWalletData)> for BankOfAmericaPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, google_pay_data): (&types::SetupMandateRouterData, domain::GooglePayWalletData),
+ (item, google_pay_data): (&SetupMandateRouterData, GooglePayWalletData),
) -> Result<Self, Self::Error> {
let order_information = OrderInformationWithBill::try_from(item)?;
let client_reference_information = ClientReferenceInformation::from(item);
- let merchant_defined_information = item.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned())
- });
+ let merchant_defined_information =
+ item.request.metadata.clone().map(|metadata| {
+ convert_metadata_to_merchant_defined_info(metadata.peek().to_owned())
+ });
let payment_information = PaymentInformation::from(&google_pay_data);
let processing_information =
ProcessingInformation::try_from((Some(PaymentSolution::GooglePay), None))?;
@@ -2426,10 +2363,10 @@ impl TryFrom<(Option<PaymentSolution>, Option<String>)> for ProcessingInformatio
}
}
-impl TryFrom<&types::SetupMandateRouterData> for OrderInformationWithBill {
+impl TryFrom<&SetupMandateRouterData> for OrderInformationWithBill {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
@@ -2443,10 +2380,12 @@ impl TryFrom<&types::SetupMandateRouterData> for OrderInformationWithBill {
}
}
-impl TryFrom<&domain::Card> for PaymentInformation {
+impl TryFrom<&hyperswitch_domain_models::payment_method_data::Card> for PaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(ccard: &domain::Card) -> Result<Self, Self::Error> {
+ fn try_from(
+ ccard: &hyperswitch_domain_models::payment_method_data::Card,
+ ) -> Result<Self, Self::Error> {
let card_type = match ccard.card_network.clone().and_then(get_boa_card_type) {
Some(card_network) => Some(card_network.to_string()),
None => ccard.get_card_issuer().ok().map(String::from),
@@ -2485,8 +2424,8 @@ impl TryFrom<&Box<ApplePayPredecryptData>> for PaymentInformation {
}
}
-impl From<&domain::ApplePayWalletData> for PaymentInformation {
- fn from(apple_pay_data: &domain::ApplePayWalletData) -> Self {
+impl From<&ApplePayWalletData> for PaymentInformation {
+ fn from(apple_pay_data: &ApplePayWalletData) -> Self {
Self::ApplePayToken(Box::new(ApplePayTokenPaymentInformation {
fluid_data: FluidData {
value: Secret::from(apple_pay_data.payment_data.clone()),
@@ -2498,8 +2437,8 @@ impl From<&domain::ApplePayWalletData> for PaymentInformation {
}
}
-impl From<&domain::GooglePayWalletData> for PaymentInformation {
- fn from(google_pay_data: &domain::GooglePayWalletData) -> Self {
+impl From<&GooglePayWalletData> for PaymentInformation {
+ fn from(google_pay_data: &GooglePayWalletData) -> Self {
Self::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
@@ -2510,44 +2449,43 @@ impl From<&domain::GooglePayWalletData> for PaymentInformation {
}
}
-impl ForeignFrom<(&BankOfAmericaErrorInformationResponse, u16)> for types::ErrorResponse {
- fn foreign_from(
- (error_response, status_code): (&BankOfAmericaErrorInformationResponse, u16),
- ) -> Self {
- let detailed_error_info =
- error_response
- .error_information
- .to_owned()
- .details
- .map(|error_details| {
- error_details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", ")
- });
-
- let reason = get_error_reason(
- error_response.error_information.message.to_owned(),
- detailed_error_info,
- None,
- );
- Self {
- code: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code,
- attempt_status: None,
- connector_transaction_id: Some(error_response.id.clone()),
- }
+fn convert_to_error_response_from_error_info(
+ error_response: &BankOfAmericaErrorInformationResponse,
+ status_code: u16,
+) -> ErrorResponse {
+ let detailed_error_info =
+ error_response
+ .error_information
+ .to_owned()
+ .details
+ .map(|error_details| {
+ error_details
+ .iter()
+ .map(|details| format!("{} : {}", details.field, details.reason))
+ .collect::<Vec<_>>()
+ .join(", ")
+ });
+
+ let reason = get_error_reason(
+ error_response.error_information.message.to_owned(),
+ detailed_error_info,
+ None,
+ );
+ ErrorResponse {
+ code: error_response
+ .error_information
+ .reason
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_response
+ .error_information
+ .reason
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ reason,
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: Some(error_response.id.clone()),
}
}
diff --git a/crates/router/src/connector/cybersource.rs b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
similarity index 66%
rename from crates/router/src/connector/cybersource.rs
rename to crates/hyperswitch_connectors/src/connectors/cybersource.rs
index 078f66335f5..5a60f6d705a 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource.rs
@@ -1,40 +1,83 @@
pub mod transformers;
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ consts,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{report, Report, ResultExt};
-use masking::{ExposeInterface, PeekInterface};
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ mandate_revoke::MandateRevoke,
+ payments::{
+ Authorize, Capture, CompleteAuthorize, IncrementalAuthorization, PSync,
+ PaymentMethodToken, Session, SetupMandate, Void,
+ },
+ refunds::{Execute, RSync},
+ PreProcessing,
+ },
+ router_request_types::{
+ AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData,
+ PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
+ PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPreProcessingData,
+ PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData},
+ types::{
+ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
+ PaymentsIncrementalAuthorizationRouterData, PaymentsPreProcessingRouterData,
+ PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData,
+ SetupMandateRouterData,
+ },
+};
+#[cfg(feature = "payouts")]
+use hyperswitch_domain_models::{
+ router_flow_types::payouts::PoFulfill,
+ router_response_types::PayoutsResponseData,
+ types::{PayoutsData, PayoutsRouterData},
+};
+#[cfg(feature = "payouts")]
+use hyperswitch_interfaces::types::PayoutFulfillType;
+use hyperswitch_interfaces::{
+ api::{
+ self,
+ payments::PaymentSession,
+ refunds::{Refund, RefundExecute, RefundSync},
+ ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType,
+ PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsPreProcessingType,
+ PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
+ SetupMandateType,
+ },
+ webhooks,
+};
+use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as cybersource;
use url::Url;
-use super::utils::{convert_amount, PaymentsAuthorizeRequestData, RouterData};
use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{PaymentMethodDataType, RefundsRequestData},
- },
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
- },
- types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
+ constants::{self, headers},
+ types::ResponseRouterData,
+ utils::{
+ self, convert_amount, PaymentMethodDataType, PaymentsAuthorizeRequestData,
+ RefundsRequestData, RouterData as OtherRouterData,
},
- utils::BytesExt,
};
#[derive(Clone)]
@@ -62,16 +105,16 @@ impl Cybersource {
resource: &str,
payload: &String,
date: OffsetDateTime,
- http_method: services::Method,
+ http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let cybersource::CybersourceAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
- let is_post_method = matches!(http_method, services::Method::Post);
- let is_patch_method = matches!(http_method, services::Method::Patch);
- let is_delete_method = matches!(http_method, services::Method::Delete);
+ let is_post_method = matches!(http_method, Method::Post);
+ let is_patch_method = matches!(http_method, Method::Patch);
+ let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
@@ -117,7 +160,7 @@ impl ConnectorCommon for Cybersource {
"application/json;charset=utf-8"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cybersource.base_url.as_ref()
}
@@ -127,18 +170,18 @@ impl ConnectorCommon for Cybersource {
fn build_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
cybersource::CybersourceErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Cybersource ErrorResponse");
let error_message = if res.status_code == 401 {
- consts::CONNECTOR_UNAUTHORIZED_ERROR
+ constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
- consts::NO_ERROR_MESSAGE
+ hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(transformers::CybersourceErrorResponse::StandardError(response)) => {
@@ -173,12 +216,10 @@ impl ConnectorCommon for Cybersource {
.join(", ")
});
(
- response
- .reason
- .clone()
- .map_or(consts::NO_ERROR_CODE.to_string(), |reason| {
- reason.to_string()
- }),
+ response.reason.clone().map_or(
+ hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
+ |reason| reason.to_string(),
+ ),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
@@ -191,7 +232,7 @@ impl ConnectorCommon for Cybersource {
}
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
@@ -203,9 +244,9 @@ impl ConnectorCommon for Cybersource {
Ok(transformers::CybersourceErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
@@ -227,9 +268,9 @@ impl ConnectorCommon for Cybersource {
})
.collect::<Vec<String>>()
.join(" & ");
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
@@ -239,7 +280,7 @@ impl ConnectorCommon for Cybersource {
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
- crate::utils::handle_json_response_deserialization_failure(res, "cybersource")
+ utils::handle_json_response_deserialization_failure(res, "cybersource")
}
}
}
@@ -258,21 +299,21 @@ impl ConnectorValidation for Cybersource {
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
- connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
@@ -282,9 +323,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 date = OffsetDateTime::now_utc();
let cybersource_req = self.get_request_body(req, connectors)?;
let auth = cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?;
@@ -328,10 +369,7 @@ where
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
- if matches!(
- http_method,
- services::Method::Post | services::Method::Put | services::Method::Patch
- ) {
+ if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
@@ -358,28 +396,20 @@ impl api::Payouts for Cybersource {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Cybersource {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Cybersource
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Cybersource
{
// Not Implemented (R)
}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Cybersource
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Cybersource
{
fn get_headers(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -387,15 +417,15 @@ impl
}
fn get_url(
&self,
- _req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
+ _req: &SetupMandateRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::SetupMandateRouterData,
- _connectors: &settings::Connectors,
+ req: &SetupMandateRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = cybersource::CybersourceZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -403,35 +433,33 @@ impl
fn build_request(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<common_utils::request::Request>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::SetupMandateType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
- .set_body(types::SetupMandateType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::SetupMandateRouterData,
+ data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("CybersourceSetupMandatesResponse")
.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,
@@ -440,17 +468,17 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -466,76 +494,72 @@ impl
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl
- ConnectorIntegration<
- api::MandateRevoke,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
- > for Cybersource
+impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
+ for Cybersource
{
fn get_headers(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Delete
+ fn get_http_method(&self) -> Method {
+ Method::Delete
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}tms/v1/paymentinstruments/{}",
self.base_url(connectors),
- connector_utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
+ utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
))
}
fn build_request(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Delete)
- .url(&types::MandateRevokeType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Delete)
+ .url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::MandateRevokeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(MandateRevokeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::MandateRevokeRouterData,
+ data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
if matches!(res.status_code, 204) {
event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()})));
- Ok(types::MandateRevokeRouterData {
- response: Ok(types::MandateRevokeResponseData {
+ Ok(MandateRevokeRouterData {
+ response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..data.clone()
@@ -553,9 +577,9 @@ impl
});
router_env::logger::info!(connector_response=?response_string);
- Ok(types::MandateRevokeRouterData {
- response: Err(types::ErrorResponse {
- code: consts::NO_ERROR_CODE.to_string(),
+ Ok(MandateRevokeRouterData {
+ response: Err(ErrorResponse {
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response_string.clone(),
reason: Some(response_string),
status_code: res.status_code,
@@ -568,37 +592,28 @@ impl
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Cybersource
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cybersource {
// Not Implemented (R)
}
-impl api::PaymentSession for Cybersource {}
+impl PaymentSession for Cybersource {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Cybersource
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cybersource {}
-impl
- ConnectorIntegration<
- api::PreProcessing,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
- > for Cybersource
+impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
+ for Cybersource
{
fn get_headers(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -606,8 +621,8 @@ impl
}
fn get_url(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -627,8 +642,8 @@ impl
}
fn get_request_body(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsPreProcessingRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
@@ -650,20 +665,18 @@ impl
}
fn build_request(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsPreProcessingType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsPreProcessingType::get_headers(
+ .headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsPreProcessingType::get_request_body(
+ .set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -672,17 +685,17 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsPreProcessingRouterData,
+ data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePreProcessingResponse = res
.response
.parse_struct("Cybersource AuthEnrollmentResponse")
.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,
@@ -691,21 +704,19 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cybersource {
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)
}
@@ -715,8 +726,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!(
@@ -728,8 +739,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 amount = convert_amount(
self.amount_converter,
@@ -743,18 +754,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(),
@@ -762,11 +771,11 @@ 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,
+ res: Response,
) -> CustomResult<
- types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
+ RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: cybersource::CybersourcePaymentsResponse = res
@@ -775,7 +784,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.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,
@@ -783,17 +792,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -802,38 +811,38 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cybersource {
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)
}
- 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 connector_payment_id = req
.request
@@ -853,31 +862,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)?)
+ 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: cybersource::CybersourceTransactionResponse = res
.response
.parse_struct("Cybersource PaymentSyncResponse")
.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,
@@ -885,21 +894,19 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cybersource {
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)
}
@@ -909,8 +916,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> {
if req.is_three_ds()
&& req.request.is_card()
@@ -932,8 +939,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,
@@ -959,18 +966,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
@@ -979,10 +982,10 @@ 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> {
if data.is_three_ds()
&& data.request.is_card()
&& (data.request.connector_mandate_id().is_none()
@@ -995,7 +998,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.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,
@@ -1007,7 +1010,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.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,
@@ -1017,17 +1020,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -1043,13 +1046,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
@@ -1057,29 +1062,27 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
#[cfg(feature = "payouts")]
-impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cybersource {
fn get_url(
&self,
- _req: &types::PayoutsRouterData<api::PoFulfill>,
- connectors: &settings::Connectors,
+ _req: &PayoutsRouterData<PoFulfill>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payouts", self.base_url(connectors)))
}
fn get_headers(
&self,
- req: &types::PayoutsRouterData<api::PoFulfill>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PayoutsRouterData<PoFulfill>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
- req: &types::PayoutsRouterData<api::PoFulfill>,
- _connectors: &settings::Connectors,
+ req: &PayoutsRouterData<PoFulfill>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -1094,19 +1097,15 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp
fn build_request(
&self,
- req: &types::PayoutsRouterData<api::PoFulfill>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
+ req: &PayoutsRouterData<PoFulfill>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PayoutFulfillType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PayoutFulfillType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(PayoutFulfillType::get_headers(self, req, connectors)?)
+ .set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
@@ -1114,10 +1113,10 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp
fn handle_response(
&self,
- data: &types::PayoutsRouterData<api::PoFulfill>,
+ data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: cybersource::CybersourceFulfillResponse = res
.response
.parse_struct("CybersourceFulfillResponse")
@@ -1126,7 +1125,7 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp
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,
@@ -1135,17 +1134,17 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -1161,31 +1160,29 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Cybersource
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Cybersource
{
fn get_headers(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -1193,8 +1190,8 @@ impl
}
fn get_url(
&self,
- _req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
@@ -1203,8 +1200,8 @@ impl
}
fn get_request_body(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -1218,20 +1215,20 @@ impl
}
fn build_request(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ .headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ .set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -1240,17 +1237,17 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
+ data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.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,
@@ -1259,17 +1256,17 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -1285,34 +1282,34 @@ impl
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cybersource {
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)
}
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!(
@@ -1327,8 +1324,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 minor_amount =
req.request
@@ -1352,15 +1349,15 @@ 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)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .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)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -1368,17 +1365,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
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: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.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,
@@ -1387,17 +1384,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
@@ -1406,32 +1403,32 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl api::Refund for Cybersource {}
-impl api::RefundExecute for Cybersource {}
-impl api::RefundSync for Cybersource {}
+impl Refund for Cybersource {}
+impl RefundExecute for Cybersource {}
+impl RefundSync for Cybersource {}
#[allow(dead_code)]
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cybersource {
fn get_headers(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -1441,8 +1438,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -1454,8 +1451,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundExecuteRouterData,
- _connectors: &settings::Connectors,
+ req: &RefundExecuteRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
@@ -1469,17 +1466,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn build_request(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -1487,17 +1482,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundExecuteRouterData,
+ data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundExecuteRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRefundResponse = res
.response
.parse_struct("Cybersource 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,
@@ -1505,34 +1500,32 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[allow(dead_code)]
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Cybersource
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cybersource {
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)
}
fn get_content_type(&self) -> &'static str {
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::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
@@ -1543,31 +1536,31 @@ 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: types::Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRsyncResponse = res
.response
.parse_struct("Cybersource 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,
@@ -1575,30 +1568,30 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
- api::IncrementalAuthorization,
- types::PaymentsIncrementalAuthorizationData,
- types::PaymentsResponseData,
+ IncrementalAuthorization,
+ PaymentsIncrementalAuthorizationData,
+ PaymentsResponseData,
> for Cybersource
{
fn get_headers(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Patch
+ fn get_http_method(&self) -> Method {
+ Method::Patch
}
fn get_content_type(&self) -> &'static str {
@@ -1607,8 +1600,8 @@ impl
fn get_url(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -1620,8 +1613,8 @@ impl
fn get_request_body(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_additional_amount = MinorUnit::new(req.request.additional_amount);
let additional_amount = convert_amount(
@@ -1639,20 +1632,20 @@ impl
}
fn build_request(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Patch)
- .url(&types::IncrementalAuthorizationType::get_url(
+ RequestBuilder::new()
+ .method(Method::Patch)
+ .url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::IncrementalAuthorizationType::get_headers(
+ .headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
- .set_body(types::IncrementalAuthorizationType::get_request_body(
+ .set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -1660,14 +1653,14 @@ impl
}
fn handle_response(
&self,
- data: &types::PaymentsIncrementalAuthorizationRouterData,
+ data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
+ res: Response,
) -> CustomResult<
- types::RouterData<
- api::IncrementalAuthorization,
- types::PaymentsIncrementalAuthorizationData,
- types::PaymentsResponseData,
+ RouterData<
+ IncrementalAuthorization,
+ PaymentsIncrementalAuthorizationData,
+ PaymentsResponseData,
>,
errors::ConnectorError,
> {
@@ -1677,44 +1670,41 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- true,
- ))
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Cybersource {
+impl webhooks::IncomingWebhook for Cybersource {
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<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ 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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
similarity index 78%
rename from crates/router/src/connector/cybersource/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
index 2aa24e5ffdf..9f3d0241719 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
@@ -2,40 +2,68 @@ use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutMethodData;
use base64::Engine;
-use common_enums::FutureUsage;
+use common_enums::{enums, FutureUsage};
use common_utils::{
+ consts,
ext_traits::{OptionExt, ValueExt},
pii,
types::{SemanticVersion, StringMajorUnit},
};
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
-use hyperswitch_domain_models::address::{AddressDetails, PhoneDetails};
+use hyperswitch_domain_models::{
+ address::{AddressDetails, PhoneDetails},
+ router_flow_types::PoFulfill,
+ router_response_types::PayoutsResponseData,
+ types::PayoutsRouterData,
+};
+use hyperswitch_domain_models::{
+ payment_method_data::{
+ ApplePayWalletData, GooglePayWalletData, NetworkTokenData, PaymentMethodData,
+ SamsungPayWalletData, WalletData,
+ },
+ router_data::{
+ AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
+ ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData,
+ },
+ router_flow_types::{
+ payments::Authorize,
+ refunds::{Execute, RSync},
+ SetupMandate,
+ },
+ router_request_types::{
+ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsPreProcessingData, PaymentsSyncData, ResponseId, SetupMandateRequestData,
+ },
+ router_response_types::{
+ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsIncrementalAuthorizationRouterData,
+ PaymentsPreProcessingRouterData, RefundsRouterData, SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
+use utils::ForeignTryFrom;
#[cfg(feature = "payouts")]
-use crate::connector::utils::PayoutsData;
+use crate::types::PayoutsResponseRouterData;
+#[cfg(feature = "payouts")]
+use crate::utils::PayoutsData;
use crate::{
- connector::utils::{
- self, AddressDetailsData, ApplePayDecrypt, CardData, NetworkTokenData,
+ constants,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ unimplemented_payment_method,
+ utils::{
+ self, AddressDetailsData, ApplePayDecrypt, CardData, CardIssuer, NetworkTokenData as _,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- PaymentsPreProcessingData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData,
- RecurringMandateData, RouterData,
+ PaymentsPreProcessingRequestData, PaymentsSetupMandateRequestData, PaymentsSyncRequestData,
+ RecurringMandateData, RouterData as OtherRouterData,
},
- consts,
- core::errors,
- services,
- types::{
- self,
- api::{self, enums as api_enums},
- domain,
- storage::enums,
- transformers::{ForeignFrom, ForeignTryFrom},
- ApplePayPredecryptData,
- },
- unimplemented_payment_method,
};
#[derive(Debug, Serialize)]
@@ -53,6 +81,22 @@ impl<T> From<(StringMajorUnit, T)> for CybersourceRouterData<T> {
}
}
+impl From<CardIssuer> for String {
+ fn from(card_issuer: CardIssuer) -> Self {
+ let card_type = match card_issuer {
+ CardIssuer::AmericanExpress => "003",
+ CardIssuer::Master => "002",
+ //"042" is the type code for Masetro Cards(International). For Maestro Cards(UK-Domestic) the mapping should be "024"
+ CardIssuer::Maestro => "042",
+ CardIssuer::Visa => "001",
+ CardIssuer::Discover => "004",
+ CardIssuer::DinersClub => "005",
+ CardIssuer::CarteBlanche => "006",
+ CardIssuer::JCB => "007",
+ };
+ card_type.to_string()
+ }
+}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CybersourceConnectorMetadataObject {
pub disable_avs: Option<bool>,
@@ -79,9 +123,9 @@ pub struct CybersourceZeroMandateRequest {
client_reference_information: ClientReferenceInformation,
}
-impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
+impl TryFrom<&SetupMandateRouterData> for CybersourceZeroMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.get_billing_email().or(item.request.get_email())?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
@@ -118,7 +162,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
};
let (payment_information, solution) = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
@@ -141,55 +185,54 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
)
}
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
- match item.payment_method_token.clone() {
- Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- let expiration_month = decrypt_data.get_expiry_month()?;
- let expiration_year = decrypt_data.get_four_digit_expiry_year()?;
- (
- PaymentInformation::ApplePay(Box::new(
- ApplePayPaymentInformation {
- tokenized_card: TokenizedCard {
- number: decrypt_data
- .application_primary_account_number,
- cryptogram: decrypt_data
- .payment_data
- .online_payment_cryptogram,
- transaction_type: TransactionType::ApplePay,
- expiration_year,
- expiration_month,
- },
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() {
+ Some(payment_method_token) => match payment_method_token {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ let expiration_month = decrypt_data.get_expiry_month()?;
+ let expiration_year = decrypt_data.get_four_digit_expiry_year()?;
+ (
+ PaymentInformation::ApplePay(Box::new(
+ ApplePayPaymentInformation {
+ tokenized_card: TokenizedCard {
+ number: decrypt_data.application_primary_account_number,
+ cryptogram: decrypt_data
+ .payment_data
+ .online_payment_cryptogram,
+ transaction_type: TransactionType::ApplePay,
+ expiration_year,
+ expiration_month,
},
- )),
- Some(PaymentSolution::ApplePay),
- )
- }
- 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(
- ApplePayTokenPaymentInformation {
- fluid_data: FluidData {
- value: Secret::from(apple_pay_data.payment_data),
- descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
- },
- tokenized_card: ApplePayTokenizedCard {
- transaction_type: TransactionType::ApplePay,
},
+ )),
+ Some(PaymentSolution::ApplePay),
+ )
+ }
+ PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Manual",
+ "Cybersource"
+ ))?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Cybersource"))?
+ }
+ },
+ None => (
+ PaymentInformation::ApplePayToken(Box::new(
+ ApplePayTokenPaymentInformation {
+ fluid_data: FluidData {
+ value: Secret::from(apple_pay_data.payment_data),
+ descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
- )),
- Some(PaymentSolution::ApplePay),
- ),
- }
- }
- domain::WalletData::GooglePay(google_pay_data) => (
+ tokenized_card: ApplePayTokenizedCard {
+ transaction_type: TransactionType::ApplePay,
+ },
+ },
+ )),
+ Some(PaymentSolution::ApplePay),
+ ),
+ },
+ WalletData::GooglePay(google_pay_data) => (
PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
@@ -201,52 +244,52 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest {
})),
Some(PaymentSolution::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::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::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?,
},
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))?
@@ -568,24 +611,22 @@ pub struct BillTo {
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
- country: Option<api_enums::CountryAlpha2>,
+ country: Option<enums::CountryAlpha2>,
email: pii::Email,
}
-impl From<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
- for ClientReferenceInformation
-{
- fn from(item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+impl From<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
+ fn from(item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
}
}
-impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+impl From<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>>
for ClientReferenceInformation
{
- fn from(item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>) -> Self {
+ fn from(item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
@@ -594,7 +635,7 @@ impl From<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
@@ -602,7 +643,7 @@ impl
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
@@ -941,7 +982,7 @@ fn get_commerce_indicator_for_external_authentication(
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
&CybersourceConsumerAuthValidateResponse,
)> for ProcessingInformation
@@ -949,7 +990,7 @@ impl
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, three_ds_data): (
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
Option<PaymentSolution>,
&CybersourceConsumerAuthValidateResponse,
),
@@ -1001,13 +1042,13 @@ impl
impl
From<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
@@ -1023,13 +1064,13 @@ impl
impl
From<(
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
BillTo,
),
) -> Self {
@@ -1121,35 +1162,32 @@ fn build_bill_to(
.unwrap_or(default_address))
}
-impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> {
- fn foreign_from(metadata: Value) -> Self {
- let hashmap: std::collections::BTreeMap<String, Value> =
- serde_json::from_str(&metadata.to_string())
- .unwrap_or(std::collections::BTreeMap::new());
- let mut vector: Self = Self::new();
- let mut iter = 1;
- for (key, value) in hashmap {
- vector.push(MerchantDefinedInformation {
- key: iter,
- value: format!("{key}={value}"),
- });
- iter += 1;
- }
- vector
+fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
+ let hashmap: std::collections::BTreeMap<String, Value> =
+ serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
+ let mut vector = Vec::new();
+ let mut iter = 1;
+ for (key, value) in hashmap {
+ vector.push(MerchantDefinedInformation {
+ key: iter,
+ value: format!("{key}={value}"),
+ });
+ iter += 1;
}
+ vector
}
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item
@@ -1196,7 +1234,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let consumer_authentication_information = item
.router_data
@@ -1238,14 +1276,14 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&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>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
),
) -> Result<Self, Self::Error> {
@@ -1279,7 +1317,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let consumer_authentication_information = item
.router_data
@@ -1321,15 +1359,15 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::NetworkTokenData,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ NetworkTokenData,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, token_data): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::NetworkTokenData,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -1360,7 +1398,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let consumer_authentication_information = item
.router_data
@@ -1402,14 +1440,14 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&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>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Box<hyperswitch_domain_models::router_data::PazeDecryptedData>,
),
) -> Result<Self, Self::Error> {
@@ -1473,7 +1511,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -1488,15 +1526,15 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- domain::Card,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
- &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- domain::Card,
+ &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item
@@ -1560,7 +1598,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -1575,17 +1613,17 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
@@ -1617,7 +1655,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
@@ -1649,15 +1687,15 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item
@@ -1684,7 +1722,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -1699,15 +1737,15 @@ impl
impl
TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- Box<domain::SamsungPayWalletData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ Box<SamsungPayWalletData>,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, samsung_pay_data): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- Box<domain::SamsungPayWalletData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
+ Box<SamsungPayWalletData>,
),
) -> Result<Self, Self::Error> {
let email = item
@@ -1748,7 +1786,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -1784,33 +1822,31 @@ fn get_samsung_pay_fluid_data_value(
Ok(samsung_pay_fluid_data_value)
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
- for CybersourcePaymentsRequest
-{
+impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for CybersourcePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.connector_mandate_id() {
Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)),
None => {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
+ PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
- types::PaymentMethodToken::Token(_) => {
+ PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Cybersource"
))?
}
- types::PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Cybersource"))?
}
},
@@ -1846,9 +1882,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(
- metadata,
- )
+ convert_metadata_to_merchant_defined_info(metadata)
});
let ucaf_collection_indicator = match apple_pay_data
.payment_method
@@ -1881,17 +1915,17 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
}
- domain::WalletData::GooglePay(google_pay_data) => {
+ WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
- domain::WalletData::SamsungPay(samsung_pay_data) => {
+ WalletData::SamsungPay(samsung_pay_data) => {
Self::try_from((item, samsung_pay_data))
}
- domain::WalletData::Paze(_) => {
+ WalletData::Paze(_) => {
match item.router_data.payment_method_token.clone() {
- Some(types::PaymentMethodToken::PazeDecrypt(
- paze_decrypted_data,
- )) => Self::try_from((item, paze_decrypted_data)),
+ Some(PaymentMethodToken::PazeDecrypt(paze_decrypted_data)) => {
+ Self::try_from((item, paze_decrypted_data))
+ }
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"Cybersource",
@@ -1900,41 +1934,37 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
.into()),
}
}
- 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::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(
- utils::get_unimplemented_payment_method_error_message(
- "Cybersource",
- ),
- )
- .into())
- }
+ 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::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("Cybersource"),
+ )
+ .into()),
},
// If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause.
// This is a fallback implementation in the event of catastrophe.
- domain::PaymentMethodData::MandatePayment => {
+ PaymentMethodData::MandatePayment => {
let connector_mandate_id =
item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -1943,26 +1973,26 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
)?;
Self::try_from((item, connector_mandate_id))
}
- domain::PaymentMethodData::NetworkToken(token_data) => {
+ PaymentMethodData::NetworkToken(token_data) => {
Self::try_from((item, token_data))
}
- domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card) => {
+ PaymentMethodData::CardDetailsForNetworkTransactionId(card) => {
Self::try_from((item, card))
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -1974,16 +2004,13 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
-impl
- TryFrom<(
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- )> for CybersourcePaymentsRequest
+impl TryFrom<(&CybersourceRouterData<&PaymentsAuthorizeRouterData>, String)>
+ for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
- &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
@@ -2007,7 +2034,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
@@ -2026,15 +2053,13 @@ pub struct CybersourceAuthSetupRequest {
client_reference_information: ClientReferenceInformation,
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
- for CybersourceAuthSetupRequest
-{
+impl TryFrom<&CybersourceRouterData<&PaymentsAuthorizeRouterData>> for CybersourceAuthSetupRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &CybersourceRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
@@ -2059,24 +2084,24 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
client_reference_information,
})
}
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -2103,19 +2128,20 @@ pub struct CybersourcePaymentsIncrementalAuthorizationRequest {
order_information: OrderInformationIncrementalAuthorization,
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>>
+impl TryFrom<&CybersourceRouterData<&PaymentsCaptureRouterData>>
for CybersourcePaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsCaptureRouterData>,
+ item: &CybersourceRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
+
Ok(Self {
processing_information: ProcessingInformation {
capture_options: Some(CaptureOptions {
@@ -2144,12 +2170,12 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCaptureRouterData>>
}
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRouterData>>
+impl TryFrom<&CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData>>
for CybersourcePaymentsIncrementalAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsIncrementalAuthorizationRouterData>,
+ item: &CybersourceRouterData<&PaymentsIncrementalAuthorizationRouterData>,
) -> Result<Self, Self::Error> {
let connector_merchant_config =
CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?;
@@ -2204,17 +2230,18 @@ pub struct ReversalInformation {
reason: String,
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsCancelRouterData>> for CybersourceVoidRequest {
+impl TryFrom<&CybersourceRouterData<&PaymentsCancelRouterData>> for CybersourceVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: &CybersourceRouterData<&types::PaymentsCancelRouterData>,
+ value: &CybersourceRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
+
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
@@ -2248,10 +2275,10 @@ pub struct CybersourceAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType {
+impl TryFrom<&ConnectorAuthType> for CybersourceAuthType {
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,
@@ -2301,40 +2328,42 @@ pub enum CybersourceIncrementalAuthorizationStatus {
AuthorizedPendingReview,
}
-impl ForeignFrom<(CybersourcePaymentStatus, bool)> for enums::AttemptStatus {
- fn foreign_from((status, capture): (CybersourcePaymentStatus, bool)) -> Self {
- match status {
- CybersourcePaymentStatus::Authorized => {
- if capture {
- // Because Cybersource will return Payment Status as Authorized even in AutoCapture Payment
- Self::Charged
- } else {
- Self::Authorized
- }
- }
- CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => {
- Self::Charged
+pub fn map_cybersource_attempt_status(
+ status: CybersourcePaymentStatus,
+ capture: bool,
+) -> enums::AttemptStatus {
+ match status {
+ CybersourcePaymentStatus::Authorized => {
+ if capture {
+ // Because Cybersource will return Payment Status as Authorized even in AutoCapture Payment
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Authorized
}
- CybersourcePaymentStatus::Voided
- | CybersourcePaymentStatus::Reversed
- | CybersourcePaymentStatus::Cancelled => Self::Voided,
- CybersourcePaymentStatus::Failed
- | CybersourcePaymentStatus::Declined
- | CybersourcePaymentStatus::AuthorizedRiskDeclined
- | CybersourcePaymentStatus::Rejected
- | CybersourcePaymentStatus::InvalidRequest
- | CybersourcePaymentStatus::ServerError => Self::Failure,
- CybersourcePaymentStatus::PendingAuthentication => Self::AuthenticationPending,
- CybersourcePaymentStatus::PendingReview
- | CybersourcePaymentStatus::StatusNotReceived
- | CybersourcePaymentStatus::Challenge
- | CybersourcePaymentStatus::Accepted
- | CybersourcePaymentStatus::Pending
- | CybersourcePaymentStatus::AuthorizedPendingReview => Self::Pending,
}
+ CybersourcePaymentStatus::Succeeded | CybersourcePaymentStatus::Transmitted => {
+ enums::AttemptStatus::Charged
+ }
+ CybersourcePaymentStatus::Voided
+ | CybersourcePaymentStatus::Reversed
+ | CybersourcePaymentStatus::Cancelled => enums::AttemptStatus::Voided,
+ CybersourcePaymentStatus::Failed
+ | CybersourcePaymentStatus::Declined
+ | CybersourcePaymentStatus::AuthorizedRiskDeclined
+ | CybersourcePaymentStatus::Rejected
+ | CybersourcePaymentStatus::InvalidRequest
+ | CybersourcePaymentStatus::ServerError => enums::AttemptStatus::Failure,
+ CybersourcePaymentStatus::PendingAuthentication => {
+ enums::AttemptStatus::AuthenticationPending
+ }
+ CybersourcePaymentStatus::PendingReview
+ | CybersourcePaymentStatus::StatusNotReceived
+ | CybersourcePaymentStatus::Challenge
+ | CybersourcePaymentStatus::Accepted
+ | CybersourcePaymentStatus::Pending
+ | CybersourcePaymentStatus::AuthorizedPendingReview => enums::AttemptStatus::Pending,
}
}
-
impl From<CybersourceIncrementalAuthorizationStatus> for common_enums::AuthorizationStatus {
fn from(item: CybersourceIncrementalAuthorizationStatus) -> Self {
match item {
@@ -2446,84 +2475,17 @@ pub struct CybersourceErrorInformation {
details: Option<Vec<Details>>,
}
-impl<F, T>
- ForeignFrom<(
- &CybersourceErrorInformationResponse,
- types::ResponseRouterData<F, CybersourcePaymentsResponse, T, types::PaymentsResponseData>,
- Option<enums::AttemptStatus>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
-{
- fn foreign_from(
- (error_response, item, transaction_status): (
- &CybersourceErrorInformationResponse,
- types::ResponseRouterData<
- F,
- CybersourcePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
- Option<enums::AttemptStatus>,
- ),
- ) -> Self {
- let detailed_error_info =
- error_response
- .error_information
- .details
- .to_owned()
- .map(|details| {
- details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", ")
- });
-
- let reason = get_error_reason(
- error_response.error_information.message.clone(),
- detailed_error_info,
- None,
- );
- let response = Err(types::ErrorResponse {
- code: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code: item.http_code,
- attempt_status: None,
- connector_transaction_id: Some(error_response.id.clone()),
- });
- match transaction_status {
- Some(status) => Self {
- response,
- status,
- ..item.data
- },
- None => Self {
- response,
- ..item.data
- },
- }
- }
-}
-
fn get_error_response_if_failure(
(info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16),
-) -> Option<types::ErrorResponse> {
+) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
- Some(types::ErrorResponse::foreign_from((
+ Some(get_error_response(
&info_response.error_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
- )))
+ ))
} else {
None
}
@@ -2531,7 +2493,7 @@ fn get_error_response_if_failure(
fn get_payment_response(
(info_response, status, http_code): (&CybersourcePaymentsResponse, enums::AttemptStatus, u16),
-) -> Result<types::PaymentsResponseData, types::ErrorResponse> {
+) -> Result<PaymentsResponseData, ErrorResponse> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(error),
@@ -2542,7 +2504,7 @@ fn get_payment_response(
info_response
.token_information
.clone()
- .map(|token_info| types::MandateReference {
+ .map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
@@ -2551,8 +2513,8 @@ fn get_payment_response(
connector_mandate_request_reference_id: None,
});
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -2575,38 +2537,37 @@ fn get_payment_response(
impl
TryFrom<
- types::ResponseRouterData<
- api::Authorize,
+ ResponseRouterData<
+ Authorize,
CybersourcePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- >
- for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- api::Authorize,
+ item: ResponseRouterData<
+ Authorize,
CybersourcePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
let connector_response = item
.response
.processor_information
.as_ref()
- .map(types::AdditionalPaymentMethodConnectorResponse::from)
- .map(types::ConnectorResponseData::with_additional_payment_method_data);
+ .map(AdditionalPaymentMethodConnectorResponse::from)
+ .map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
@@ -2619,41 +2580,39 @@ impl
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourceAuthSetupResponse,
- 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,
CybersourceAuthSetupResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
CybersourceAuthSetupResponse::ClientAuthSetupInfo(info_response) => Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data: Box::new(Some(
- services::RedirectForm::CybersourceAuthSetup {
- access_token: info_response
- .consumer_authentication_information
- .access_token,
- ddc_url: info_response
- .consumer_authentication_information
- .device_data_collection_url,
- reference_id: info_response
- .consumer_authentication_information
- .reference_id,
- },
- )),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
+ redirection_data: Box::new(Some(RedirectForm::CybersourceAuthSetup {
+ access_token: info_response
+ .consumer_authentication_information
+ .access_token,
+ ddc_url: info_response
+ .consumer_authentication_information
+ .device_data_collection_url,
+ reference_id: info_response
+ .consumer_authentication_information
+ .reference_id,
+ })),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
@@ -2689,11 +2648,13 @@ impl<F>
);
let error_message = error_response.error_information.reason;
Ok(Self {
- response: Err(types::ErrorResponse {
+ response: Err(ErrorResponse {
code: error_message
.clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_message.unwrap_or(
+ hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string(),
+ ),
reason,
status_code: item.http_code,
attempt_status: None,
@@ -2750,12 +2711,12 @@ pub enum CybersourcePreProcessingRequest {
AuthValidate(Box<CybersourceAuthValidateRequest>),
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
+impl TryFrom<&CybersourceRouterData<&PaymentsPreProcessingRouterData>>
for CybersourcePreProcessingRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsPreProcessingRouterData>,
+ item: &CybersourceRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let client_reference_information = ClientReferenceInformation {
code: Some(item.router_data.connector_request_reference_id.clone()),
@@ -2766,7 +2727,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
},
)?;
let payment_information = match payment_method_data {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let card_type = match ccard
.card_network
.clone()
@@ -2787,24 +2748,24 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
},
)))
}
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
))
@@ -2889,12 +2850,12 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsPreProcessingRouterData>>
}
}
-impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+impl TryFrom<&CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>>
for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ item: &CybersourceRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_method_data = item.router_data.request.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -2902,25 +2863,25 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>
},
)?;
match payment_method_data {
- domain::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
- domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
+ PaymentMethodData::Wallet(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
@@ -2995,21 +2956,21 @@ impl From<CybersourceAuthEnrollmentStatus> for enums::AttemptStatus {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourcePreProcessingResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CybersourcePreProcessingResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response {
@@ -3017,13 +2978,13 @@ impl<F>
let status = enums::AttemptStatus::from(info_response.status);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
- let response = Err(types::ErrorResponse::foreign_from((
+ let response = Err(get_error_response(
&info_response.error_information,
&risk_info,
Some(status),
item.http_code,
info_response.id.clone(),
- )));
+ ));
Ok(Self {
status,
@@ -3047,7 +3008,7 @@ impl<F>
.step_up_url,
) {
(Some(token), Some(step_up_url)) => {
- Some(services::RedirectForm::CybersourceConsumerAuth {
+ Some(RedirectForm::CybersourceConsumerAuth {
access_token: token.expose(),
step_up_url,
})
@@ -3062,8 +3023,8 @@ impl<F>
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
@@ -3098,11 +3059,12 @@ impl<F>
None,
);
let error_message = error_response.error_information.reason.to_owned();
- let response = Err(types::ErrorResponse {
+ let response = Err(ErrorResponse {
code: error_message
.clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_message
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason,
status_code: item.http_code,
attempt_status: None,
@@ -3120,37 +3082,37 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
+ CompleteAuthorizeData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<F, CompleteAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
+ CompleteAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
let connector_response = item
.response
.processor_information
.as_ref()
- .map(types::AdditionalPaymentMethodConnectorResponse::from)
- .map(types::ConnectorResponseData::with_additional_payment_method_data);
+ .map(AdditionalPaymentMethodConnectorResponse::from)
+ .map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
@@ -3161,7 +3123,7 @@ impl<F>
}
}
-impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnectorResponse {
+impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse {
fn from(processor_information: &ClientProcessorInformation) -> Self {
let payment_checks = Some(
serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}),
@@ -3176,30 +3138,30 @@ impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnect
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
true,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
Ok(Self {
status,
@@ -3211,30 +3173,30 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CybersourcePaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
Ok(Self {
status,
@@ -3247,33 +3209,28 @@ impl<F>
// zero dollar response
impl
TryFrom<
- types::ResponseRouterData<
- api::SetupMandate,
+ ResponseRouterData<
+ SetupMandate,
CybersourcePaymentsResponse,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
+ SetupMandateRequestData,
+ PaymentsResponseData,
>,
- >
- for types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >
+ > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- api::SetupMandate,
+ item: ResponseRouterData<
+ SetupMandate,
CybersourcePaymentsResponse,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
+ SetupMandateRequestData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference =
item.response
.token_information
.clone()
- .map(|token_info| types::MandateReference {
+ .map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
@@ -3281,13 +3238,13 @@ impl
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
- let mut mandate_status = enums::AttemptStatus::foreign_from((
+ let mut mandate_status = map_cybersource_attempt_status(
item.response
.status
.clone()
.unwrap_or(CybersourcePaymentStatus::StatusNotReceived),
false,
- ));
+ );
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
@@ -3299,17 +3256,15 @@ impl
.response
.processor_information
.as_ref()
- .map(types::AdditionalPaymentMethodConnectorResponse::from)
- .map(types::ConnectorResponseData::with_additional_payment_method_data);
+ .map(AdditionalPaymentMethodConnectorResponse::from)
+ .map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
- None => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.clone(),
- ),
+ None => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -3339,47 +3294,38 @@ impl
}
impl<F, T>
- ForeignTryFrom<(
- types::ResponseRouterData<
+ TryFrom<
+ ResponseRouterData<
F,
CybersourcePaymentsIncrementalAuthorizationResponse,
T,
- types::PaymentsResponseData,
+ PaymentsResponseData,
>,
- bool,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ > for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn foreign_try_from(
- data: (
- types::ResponseRouterData<
- F,
- CybersourcePaymentsIncrementalAuthorizationResponse,
- T,
- types::PaymentsResponseData,
- >,
- bool,
- ),
+ fn try_from(
+ item: ResponseRouterData<
+ F,
+ CybersourcePaymentsIncrementalAuthorizationResponse,
+ T,
+ PaymentsResponseData,
+ >,
) -> Result<Self, Self::Error> {
- let item = data.0;
Ok(Self {
response: match item.response.error_information {
- Some(error) => Ok(
- types::PaymentsResponseData::IncrementalAuthorizationResponse {
- status: common_enums::AuthorizationStatus::Failure,
- error_code: error.reason,
- error_message: error.message,
- connector_authorization_id: None,
- },
- ),
- _ => Ok(
- types::PaymentsResponseData::IncrementalAuthorizationResponse {
- status: item.response.status.into(),
- error_code: None,
- error_message: None,
- connector_authorization_id: None,
- },
- ),
+ Some(error) => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
+ status: common_enums::AuthorizationStatus::Failure,
+ error_code: error.reason,
+ error_message: error.message,
+ connector_authorization_id: None,
+ }),
+ None => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
+ status: item.response.status.into(),
+ error_code: None,
+ error_message: None,
+ connector_authorization_id: None,
+ }),
},
..item.data
})
@@ -3403,49 +3349,47 @@ pub struct ApplicationInformation {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
CybersourceTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
CybersourceTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(status) => {
- let status = enums::AttemptStatus::foreign_from((
- status,
- item.data.request.is_auto_capture()?,
- ));
+ let status =
+ map_cybersource_attempt_status(status, item.data.request.is_auto_capture()?);
let incremental_authorization_allowed =
Some(status == enums::AttemptStatus::Authorized);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
- response: Err(types::ErrorResponse::foreign_from((
+ response: Err(get_error_response(
&item.response.error_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
- ))),
+ )),
status: enums::AttemptStatus::Failure,
..item.data
})
} else {
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
@@ -3466,10 +3410,8 @@ impl<F>
}
None => Ok(Self {
status: item.data.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: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -3491,11 +3433,9 @@ pub struct CybersourceRefundRequest {
client_reference_information: ClientReferenceInformation,
}
-impl<F> TryFrom<&CybersourceRouterData<&types::RefundsRouterData<F>>> for CybersourceRefundRequest {
+impl<F> TryFrom<&CybersourceRouterData<&RefundsRouterData<F>>> for CybersourceRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &CybersourceRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &CybersourceRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
@@ -3543,24 +3483,24 @@ pub struct CybersourceRefundResponse {
error_information: Option<CybersourceErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, CybersourceRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, CybersourceRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, CybersourceRefundResponse>,
+ item: RefundsResponseRouterData<Execute, CybersourceRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
})
@@ -3587,12 +3527,12 @@ pub struct CybersourceRsyncResponse {
error_information: Option<CybersourceErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, CybersourceRsyncResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, CybersourceRsyncResponse>,
+ item: RefundsResponseRouterData<RSync, CybersourceRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
@@ -3603,35 +3543,35 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRsyncRespon
let refund_status = enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == CybersourceRefundStatus::Voided {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&Some(CybersourceErrorInformation {
- message: Some(consts::REFUND_VOIDED.to_string()),
- reason: Some(consts::REFUND_VOIDED.to_string()),
+ message: Some(constants::REFUND_VOIDED.to_string()),
+ reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
} else {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
}
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
- None => Ok(types::RefundsResponseData {
+ None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
@@ -3669,7 +3609,7 @@ pub struct CybersourceRecipientInfo {
locality: String,
administrative_area: Secret<String>,
postal_code: Secret<String>,
- country: api_enums::CountryAlpha2,
+ country: enums::CountryAlpha2,
phone_number: Option<Secret<String>>,
}
@@ -3712,12 +3652,12 @@ pub enum CybersourcePayoutBusinessType {
}
#[cfg(feature = "payouts")]
-impl TryFrom<&CybersourceRouterData<&types::PayoutsRouterData<api::PoFulfill>>>
+impl TryFrom<&CybersourceRouterData<&PayoutsRouterData<PoFulfill>>>
for CybersourcePayoutFulfillRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CybersourceRouterData<&types::PayoutsRouterData<api::PoFulfill>>,
+ item: &CybersourceRouterData<&PayoutsRouterData<PoFulfill>>,
) -> Result<Self, Self::Error> {
let payout_type = item.router_data.request.get_payout_type()?;
match payout_type {
@@ -3834,28 +3774,24 @@ pub enum CybersourcePayoutStatus {
}
#[cfg(feature = "payouts")]
-impl ForeignFrom<CybersourcePayoutStatus> for enums::PayoutStatus {
- fn foreign_from(status: CybersourcePayoutStatus) -> Self {
- match status {
- CybersourcePayoutStatus::Accepted => Self::Success,
- CybersourcePayoutStatus::Declined | CybersourcePayoutStatus::InvalidRequest => {
- Self::Failed
- }
+fn map_payout_status(status: CybersourcePayoutStatus) -> enums::PayoutStatus {
+ match status {
+ CybersourcePayoutStatus::Accepted => enums::PayoutStatus::Success,
+ CybersourcePayoutStatus::Declined | CybersourcePayoutStatus::InvalidRequest => {
+ enums::PayoutStatus::Failed
}
}
}
#[cfg(feature = "payouts")]
-impl<F> TryFrom<types::PayoutsResponseRouterData<F, CybersourceFulfillResponse>>
- for types::PayoutsRouterData<F>
-{
+impl<F> TryFrom<PayoutsResponseRouterData<F, CybersourceFulfillResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PayoutsResponseRouterData<F, CybersourceFulfillResponse>,
+ item: PayoutsResponseRouterData<F, CybersourceFulfillResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PayoutsResponseData {
- status: Some(enums::PayoutStatus::foreign_from(item.response.status)),
+ response: Ok(PayoutsResponseData {
+ status: Some(map_payout_status(item.response.status)),
connector_payout_id: Some(item.response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
@@ -3940,70 +3876,62 @@ pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
-impl
- ForeignFrom<(
- &Option<CybersourceErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- )> for types::ErrorResponse
-{
- fn foreign_from(
- (error_data, risk_information, attempt_status, status_code, transaction_id): (
- &Option<CybersourceErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- ),
- ) -> Self {
- let avs_message = risk_information
- .clone()
- .map(|client_risk_information| {
- client_risk_information.rules.map(|rules| {
- rules
- .iter()
- .map(|risk_info| {
- risk_info.name.clone().map_or("".to_string(), |name| {
- format!(" , {}", name.clone().expose())
- })
+pub fn get_error_response(
+ error_data: &Option<CybersourceErrorInformation>,
+ risk_information: &Option<ClientRiskInformation>,
+ attempt_status: Option<enums::AttemptStatus>,
+ status_code: u16,
+ transaction_id: String,
+) -> ErrorResponse {
+ let avs_message = risk_information
+ .clone()
+ .map(|client_risk_information| {
+ client_risk_information.rules.map(|rules| {
+ rules
+ .iter()
+ .map(|risk_info| {
+ risk_info.name.clone().map_or("".to_string(), |name| {
+ format!(" , {}", name.clone().expose())
})
- .collect::<Vec<String>>()
- .join("")
- })
+ })
+ .collect::<Vec<String>>()
+ .join("")
})
- .unwrap_or(Some("".to_string()));
+ })
+ .unwrap_or(Some("".to_string()));
+
+ let detailed_error_info = error_data.as_ref().and_then(|error_data| {
+ error_data.details.as_ref().map(|details| {
+ details
+ .iter()
+ .map(|detail| format!("{} : {}", detail.field, detail.reason))
+ .collect::<Vec<_>>()
+ .join(", ")
+ })
+ });
- let detailed_error_info = error_data
- .clone()
- .map(|error_data| match error_data.details {
- Some(details) => details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", "),
- None => "".to_string(),
- });
+ let reason = get_error_reason(
+ error_data
+ .as_ref()
+ .and_then(|error_info| error_info.message.clone()),
+ detailed_error_info,
+ avs_message,
+ );
- let reason = get_error_reason(
- error_data.clone().and_then(|error_info| error_info.message),
- detailed_error_info,
- avs_message,
- );
- let error_message = error_data.clone().and_then(|error_info| error_info.reason);
- Self {
- code: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code,
- attempt_status,
- connector_transaction_id: Some(transaction_id.clone()),
- }
+ let error_message = error_data
+ .as_ref()
+ .and_then(|error_info| error_info.reason.clone());
+
+ ErrorResponse {
+ code: error_message
+ .clone()
+ .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_message
+ .unwrap_or_else(|| hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ reason,
+ status_code,
+ attempt_status,
+ connector_transaction_id: Some(transaction_id),
}
}
diff --git a/crates/router/src/connector/wellsfargo.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
similarity index 66%
rename from crates/router/src/connector/wellsfargo.rs
rename to crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
index b47b3662253..8566ec70341 100644
--- a/crates/router/src/connector/wellsfargo.rs
+++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
@@ -1,42 +1,69 @@
pub mod transformers;
use base64::Engine;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ consts,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{report, Report, ResultExt};
-use masking::{ExposeInterface, PeekInterface};
-use ring::{digest, hmac};
-use time::OffsetDateTime;
-use transformers as wellsfargo;
-use url::Url;
-
-use super::utils::convert_amount;
-use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{PaymentMethodDataType, RefundsRequestData},
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ mandate_revoke::MandateRevoke,
+ payments::{
+ Authorize, Capture, IncrementalAuthorization, 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, ConnectorSpecifications, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData, RefundsData,
+ SetupMandateRequestData,
},
+ router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData},
types::{
+ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData,
+ PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData,
+ SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- transformers::ForeignTryFrom,
+ refunds::{Refund, RefundExecute, RefundSync},
+ ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType,
+ PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType,
+ Response, SetupMandateType,
},
- utils::BytesExt,
+ webhooks,
};
+use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
+use ring::{digest, hmac};
+use time::OffsetDateTime;
+use transformers as wellsfargo;
+use url::Url;
+use crate::{
+ constants::{self, headers},
+ types::ResponseRouterData,
+ utils::{self, convert_amount, PaymentMethodDataType, RefundsRequestData},
+};
#[derive(Clone)]
pub struct Wellsfargo {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
@@ -61,16 +88,16 @@ impl Wellsfargo {
resource: &str,
payload: &String,
date: OffsetDateTime,
- http_method: services::Method,
+ http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let wellsfargo::WellsfargoAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
- let is_post_method = matches!(http_method, services::Method::Post);
- let is_patch_method = matches!(http_method, services::Method::Patch);
- let is_delete_method = matches!(http_method, services::Method::Delete);
+ let is_post_method = matches!(http_method, Method::Post);
+ let is_patch_method = matches!(http_method, Method::Patch);
+ let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
@@ -116,7 +143,7 @@ impl ConnectorCommon for Wellsfargo {
"application/json;charset=utf-8"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.wellsfargo.base_url.as_ref()
}
@@ -126,18 +153,18 @@ impl ConnectorCommon for Wellsfargo {
fn build_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
wellsfargo::WellsfargoErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Wellsfargo ErrorResponse");
let error_message = if res.status_code == 401 {
- consts::CONNECTOR_UNAUTHORIZED_ERROR
+ constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
- consts::NO_ERROR_MESSAGE
+ hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(transformers::WellsfargoErrorResponse::StandardError(response)) => {
@@ -172,12 +199,10 @@ impl ConnectorCommon for Wellsfargo {
.join(", ")
});
(
- response
- .reason
- .clone()
- .map_or(consts::NO_ERROR_CODE.to_string(), |reason| {
- reason.to_string()
- }),
+ response.reason.clone().map_or(
+ hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
+ |reason| reason.to_string(),
+ ),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
@@ -190,7 +215,7 @@ impl ConnectorCommon for Wellsfargo {
}
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
@@ -202,9 +227,9 @@ impl ConnectorCommon for Wellsfargo {
Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
@@ -226,9 +251,9 @@ impl ConnectorCommon for Wellsfargo {
})
.collect::<Vec<String>>()
.join(" & ");
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
@@ -238,7 +263,7 @@ impl ConnectorCommon for Wellsfargo {
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
- crate::utils::handle_json_response_deserialization_failure(res, "wellsfargo")
+ utils::handle_json_response_deserialization_failure(res, "wellsfargo")
}
}
}
@@ -257,21 +282,21 @@ impl ConnectorValidation for Wellsfargo {
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
+ utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
- connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
@@ -281,9 +306,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 date = OffsetDateTime::now_utc();
let wellsfargo_req = self.get_request_body(req, connectors)?;
let auth = wellsfargo::WellsfargoAuthType::try_from(&req.connector_auth_type)?;
@@ -327,10 +352,7 @@ where
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
- if matches!(
- http_method,
- services::Method::Post | services::Method::Put | services::Method::Patch
- ) {
+ if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
@@ -351,28 +373,20 @@ impl api::ConnectorAccessToken for Wellsfargo {}
impl api::PaymentToken for Wellsfargo {}
impl api::ConnectorMandateRevoke for Wellsfargo {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Wellsfargo
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Wellsfargo
{
// Not Implemented (R)
}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Wellsfargo
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Wellsfargo
{
fn get_headers(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -380,15 +394,15 @@ impl
}
fn get_url(
&self,
- _req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
+ _req: &SetupMandateRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::SetupMandateRouterData,
- _connectors: &settings::Connectors,
+ req: &SetupMandateRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wellsfargo::WellsfargoZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -396,35 +410,33 @@ impl
fn build_request(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<common_utils::request::Request>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::SetupMandateType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
- .set_body(types::SetupMandateType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::SetupMandateRouterData,
+ data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("WellsfargoSetupMandatesResponse")
.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,
@@ -433,17 +445,17 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
@@ -459,76 +471,72 @@ impl
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl
- ConnectorIntegration<
- api::MandateRevoke,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
- > for Wellsfargo
+impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
+ for Wellsfargo
{
fn get_headers(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Delete
+ fn get_http_method(&self) -> Method {
+ Method::Delete
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}tms/v1/paymentinstruments/{}",
self.base_url(connectors),
- connector_utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
+ utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
))
}
fn build_request(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Delete)
- .url(&types::MandateRevokeType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Delete)
+ .url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::MandateRevokeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(MandateRevokeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::MandateRevokeRouterData,
+ data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
if matches!(res.status_code, 204) {
event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()})));
- Ok(types::MandateRevokeRouterData {
- response: Ok(types::MandateRevokeResponseData {
+ Ok(MandateRevokeRouterData {
+ response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..data.clone()
@@ -546,9 +554,9 @@ impl
});
router_env::logger::info!(connector_response=?response_string);
- Ok(types::MandateRevokeRouterData {
- response: Err(types::ErrorResponse {
- code: consts::NO_ERROR_CODE.to_string(),
+ Ok(MandateRevokeRouterData {
+ response: Err(ErrorResponse {
+ code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response_string.clone(),
reason: Some(response_string),
status_code: res.status_code,
@@ -561,33 +569,26 @@ impl
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Wellsfargo
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargo {
// Not Implemented (R)
}
impl api::PaymentSession for Wellsfargo {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Wellsfargo
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargo {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargo {
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)
}
@@ -597,8 +598,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!(
@@ -610,8 +611,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 amount = convert_amount(
self.amount_converter,
@@ -627,18 +628,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(),
@@ -646,11 +645,11 @@ 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,
+ res: Response,
) -> CustomResult<
- types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
+ RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
@@ -659,7 +658,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
.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,
@@ -667,17 +666,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
@@ -686,38 +685,38 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargo {
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)
}
- 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 connector_payment_id = req
.request
@@ -737,31 +736,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)?)
+ 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: wellsfargo::WellsfargoTransactionResponse = res
.response
.parse_struct("Wellsfargo PaymentSyncResponse")
.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,
@@ -769,21 +768,19 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargo {
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)
}
@@ -793,8 +790,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!(
"{}pts/v2/payments/",
@@ -804,8 +801,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,
@@ -821,18 +818,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
@@ -841,17 +834,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: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.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,
@@ -860,17 +853,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
@@ -886,34 +879,34 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
},
None => None,
};
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
})
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargo {
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)
}
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!(
@@ -928,8 +921,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 amount = convert_amount(
self.amount_converter,
@@ -953,15 +946,15 @@ 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)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .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)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -969,17 +962,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
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: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.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,
@@ -988,17 +981,17 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
@@ -1007,31 +1000,31 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
- code: response.status.unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ code: response
+ .status
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
})
}
}
-impl api::Refund for Wellsfargo {}
-impl api::RefundExecute for Wellsfargo {}
-impl api::RefundSync for Wellsfargo {}
+impl Refund for Wellsfargo {}
+impl RefundExecute for Wellsfargo {}
+impl RefundSync for Wellsfargo {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargo {
fn get_headers(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -1041,8 +1034,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -1054,8 +1047,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundExecuteRouterData,
- _connectors: &settings::Connectors,
+ req: &RefundExecuteRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -1069,17 +1062,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn build_request(
&self,
- req: &types::RefundExecuteRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundExecuteRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
@@ -1087,17 +1078,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn handle_response(
&self,
- data: &types::RefundExecuteRouterData,
+ data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundExecuteRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoRefundResponse = res
.response
.parse_struct("Wellsfargo 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,
@@ -1105,33 +1096,31 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Wellsfargo
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargo {
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)
}
fn get_content_type(&self) -> &'static str {
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::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
@@ -1142,31 +1131,31 @@ 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: types::Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoRsyncResponse = res
.response
.parse_struct("Wellsfargo 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,
@@ -1174,30 +1163,30 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
- api::IncrementalAuthorization,
- types::PaymentsIncrementalAuthorizationData,
- types::PaymentsResponseData,
+ IncrementalAuthorization,
+ PaymentsIncrementalAuthorizationData,
+ PaymentsResponseData,
> for Wellsfargo
{
fn get_headers(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
- fn get_http_method(&self) -> services::Method {
- services::Method::Patch
+ fn get_http_method(&self) -> Method {
+ Method::Patch
}
fn get_content_type(&self) -> &'static str {
@@ -1206,8 +1195,8 @@ impl
fn get_url(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -1219,8 +1208,8 @@ impl
fn get_request_body(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -1237,20 +1226,20 @@ impl
}
fn build_request(
&self,
- req: &types::PaymentsIncrementalAuthorizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsIncrementalAuthorizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Patch)
- .url(&types::IncrementalAuthorizationType::get_url(
+ RequestBuilder::new()
+ .method(Method::Patch)
+ .url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::IncrementalAuthorizationType::get_headers(
+ .headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
- .set_body(types::IncrementalAuthorizationType::get_request_body(
+ .set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -1258,14 +1247,14 @@ impl
}
fn handle_response(
&self,
- data: &types::PaymentsIncrementalAuthorizationRouterData,
+ data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
+ res: Response,
) -> CustomResult<
- types::RouterData<
- api::IncrementalAuthorization,
- types::PaymentsIncrementalAuthorizationData,
- types::PaymentsResponseData,
+ RouterData<
+ IncrementalAuthorization,
+ PaymentsIncrementalAuthorizationData,
+ PaymentsResponseData,
>,
errors::ConnectorError,
> {
@@ -1275,44 +1264,41 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- true,
- ))
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Wellsfargo {
+impl webhooks::IncomingWebhook for Wellsfargo {
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<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ 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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
similarity index 73%
rename from crates/router/src/connector/wellsfargo/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
index 0500b098bb1..6ce9a4d7aa9 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
@@ -1,30 +1,47 @@
use api_models::payments;
use base64::Engine;
-use common_enums::FutureUsage;
+use common_enums::{enums, FutureUsage};
use common_utils::{
- pii,
+ consts, pii,
types::{SemanticVersion, StringMajorUnit},
};
+use hyperswitch_domain_models::{
+ payment_method_data::{
+ ApplePayWalletData, BankDebitData, GooglePayWalletData, PaymentMethodData, WalletData,
+ },
+ router_data::{
+ AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType,
+ ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData,
+ },
+ router_flow_types::{
+ payments::Authorize,
+ refunds::{Execute, RSync},
+ SetupMandate,
+ },
+ router_request_types::{
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData,
+ ResponseId, SetupMandateRequestData,
+ },
+ router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsIncrementalAuthorizationRouterData, RefundsRouterData, SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
- connector::utils::{
+ constants,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ unimplemented_payment_method,
+ utils::{
self, AddressDetailsData, ApplePayDecrypt, CardData, PaymentsAuthorizeRequestData,
- PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData, RouterData,
+ PaymentsSetupMandateRequestData, PaymentsSyncRequestData, RecurringMandateData,
+ RouterData as OtherRouterData,
},
- consts,
- core::errors,
- types::{
- self,
- api::{self, enums as api_enums},
- domain,
- storage::enums,
- transformers::{ForeignFrom, ForeignTryFrom},
- ApplePayPredecryptData,
- },
- unimplemented_payment_method,
};
#[derive(Debug, Serialize)]
@@ -51,9 +68,9 @@ pub struct WellsfargoZeroMandateRequest {
client_reference_information: ClientReferenceInformation,
}
-impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
+impl TryFrom<&SetupMandateRouterData> for WellsfargoZeroMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
let email = item.request.get_email()?;
let bill_to = build_bill_to(item.get_optional_billing(), email)?;
@@ -85,7 +102,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
};
let (payment_information, solution) = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let card_issuer = ccard.get_card_issuer();
let card_type = match card_issuer {
Ok(issuer) => Some(String::from(issuer)),
@@ -105,55 +122,54 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
)
}
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
- match item.payment_method_token.clone() {
- Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- let expiration_month = decrypt_data.get_expiry_month()?;
- let expiration_year = decrypt_data.get_four_digit_expiry_year()?;
- (
- PaymentInformation::ApplePay(Box::new(
- ApplePayPaymentInformation {
- tokenized_card: TokenizedCard {
- number: decrypt_data
- .application_primary_account_number,
- cryptogram: decrypt_data
- .payment_data
- .online_payment_cryptogram,
- transaction_type: TransactionType::ApplePay,
- expiration_year,
- expiration_month,
- },
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => match item.payment_method_token.clone() {
+ Some(payment_method_token) => match payment_method_token {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ let expiration_month = decrypt_data.get_expiry_month()?;
+ let expiration_year = decrypt_data.get_four_digit_expiry_year()?;
+ (
+ PaymentInformation::ApplePay(Box::new(
+ ApplePayPaymentInformation {
+ tokenized_card: TokenizedCard {
+ number: decrypt_data.application_primary_account_number,
+ cryptogram: decrypt_data
+ .payment_data
+ .online_payment_cryptogram,
+ transaction_type: TransactionType::ApplePay,
+ expiration_year,
+ expiration_month,
},
- )),
- Some(PaymentSolution::ApplePay),
- )
- }
- 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(
- ApplePayTokenPaymentInformation {
- fluid_data: FluidData {
- value: Secret::from(apple_pay_data.payment_data),
- descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
- },
- tokenized_card: ApplePayTokenizedCard {
- transaction_type: TransactionType::ApplePay,
},
+ )),
+ Some(PaymentSolution::ApplePay),
+ )
+ }
+ PaymentMethodToken::Token(_) => Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Manual",
+ "Wellsfargo"
+ ))?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
+ }
+ },
+ None => (
+ PaymentInformation::ApplePayToken(Box::new(
+ ApplePayTokenPaymentInformation {
+ fluid_data: FluidData {
+ value: Secret::from(apple_pay_data.payment_data),
+ descriptor: Some(FLUID_DATA_DESCRIPTOR.to_string()),
},
- )),
- Some(PaymentSolution::ApplePay),
- ),
- }
- }
- domain::WalletData::GooglePay(google_pay_data) => (
+ tokenized_card: ApplePayTokenizedCard {
+ transaction_type: TransactionType::ApplePay,
+ },
+ },
+ )),
+ Some(PaymentSolution::ApplePay),
+ ),
+ },
+ WalletData::GooglePay(google_pay_data) => (
PaymentInformation::GooglePay(Box::new(GooglePayPaymentInformation {
fluid_data: FluidData {
value: Secret::from(
@@ -165,52 +181,52 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest {
})),
Some(PaymentSolution::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::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::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
))?,
},
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
))?
@@ -515,15 +531,13 @@ pub struct BillTo {
administrative_area: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
postal_code: Option<Secret<String>>,
- country: Option<api_enums::CountryAlpha2>,
+ country: Option<enums::CountryAlpha2>,
email: pii::Email,
phone_number: Option<Secret<String>>,
}
-impl From<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
- for ClientReferenceInformation
-{
- fn from(item: &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>) -> Self {
+impl From<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for ClientReferenceInformation {
+ fn from(item: &WellsfargoRouterData<&PaymentsAuthorizeRouterData>) -> Self {
Self {
code: Some(item.router_data.connector_request_reference_id.clone()),
}
@@ -532,7 +546,7 @@ impl From<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
impl
TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
)> for ProcessingInformation
@@ -540,7 +554,7 @@ impl
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, solution, network): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
Option<String>,
),
@@ -781,13 +795,13 @@ fn get_commerce_indicator_for_external_authentication(
impl
From<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
)> for OrderInformationWithBill
{
fn from(
(item, bill_to): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Option<BillTo>,
),
) -> Self {
@@ -850,35 +864,32 @@ fn build_bill_to(
ad
}
-impl ForeignFrom<Value> for Vec<MerchantDefinedInformation> {
- fn foreign_from(metadata: Value) -> Self {
- let hashmap: std::collections::BTreeMap<String, Value> =
- serde_json::from_str(&metadata.to_string())
- .unwrap_or(std::collections::BTreeMap::new());
- let mut vector: Self = Self::new();
- let mut iter = 1;
- for (key, value) in hashmap {
- vector.push(MerchantDefinedInformation {
- key: iter,
- value: format!("{key}={value}"),
- });
- iter += 1;
- }
- vector
+fn convert_metadata_to_merchant_defined_info(metadata: Value) -> Vec<MerchantDefinedInformation> {
+ let hashmap: std::collections::BTreeMap<String, Value> =
+ serde_json::from_str(&metadata.to_string()).unwrap_or(std::collections::BTreeMap::new());
+ let mut vector = Vec::new();
+ let mut iter = 1;
+ for (key, value) in hashmap {
+ vector.push(MerchantDefinedInformation {
+ key: iter,
+ value: format!("{key}={value}"),
+ });
+ iter += 1;
}
+ vector
}
impl
TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
)> for WellsfargoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::Card,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ hyperswitch_domain_models::payment_method_data::Card,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -908,7 +919,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let consumer_authentication_information = item
.router_data
@@ -950,17 +961,17 @@ impl
impl
TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
)> for WellsfargoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, apple_pay_data, apple_pay_wallet_data): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
- domain::ApplePayWalletData,
+ ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -989,7 +1000,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
let ucaf_collection_indicator = match apple_pay_wallet_data
.payment_method
.network
@@ -1021,15 +1032,15 @@ impl
impl
TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
)> for WellsfargoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, google_pay_data): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::GooglePayWalletData,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ GooglePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
@@ -1053,7 +1064,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
@@ -1084,22 +1095,22 @@ impl TryFrom<Option<common_enums::BankType>> for AccountType {
impl
TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::BankDebitData,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ BankDebitData,
)> for WellsfargoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, bank_debit_data): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- domain::BankDebitData,
+ &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
+ BankDebitData,
),
) -> Result<Self, Self::Error> {
let email = 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 = match bank_debit_data {
- domain::BankDebitData::AchBankDebit {
+ BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_type,
@@ -1115,13 +1126,11 @@ impl
},
},
))),
- domain::BankDebitData::SepaBankDebit { .. }
- | domain::BankDebitData::BacsBankDebit { .. }
- | domain::BankDebitData::BecsBankDebit { .. } => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
- ))
- }
+ BankDebitData::SepaBankDebit { .. }
+ | BankDebitData::BacsBankDebit { .. }
+ | BankDebitData::BecsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
+ )),
}?;
let processing_information =
ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
@@ -1137,33 +1146,31 @@ impl
}
}
-impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
- for WellsfargoPaymentsRequest
-{
+impl TryFrom<&WellsfargoRouterData<&PaymentsAuthorizeRouterData>> for WellsfargoPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &WellsfargoRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.connector_mandate_id() {
Some(connector_mandate_id) => Self::try_from((item, connector_mandate_id)),
None => {
match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePay(apple_pay_data) => {
+ PaymentMethodData::Card(ccard) => Self::try_from((item, ccard)),
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::ApplePay(apple_pay_data) => {
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
Self::try_from((item, decrypt_data, apple_pay_data))
}
- types::PaymentMethodToken::Token(_) => {
+ PaymentMethodToken::Token(_) => {
Err(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Wellsfargo"
))?
}
- types::PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Wellsfargo"))?
}
},
@@ -1196,9 +1203,7 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
- Vec::<MerchantDefinedInformation>::foreign_from(
- metadata,
- )
+ convert_metadata_to_merchant_defined_info(metadata)
});
let ucaf_collection_indicator = match apple_pay_data
.payment_method
@@ -1231,44 +1236,42 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
}
- domain::WalletData::GooglePay(google_pay_data) => {
+ WalletData::GooglePay(google_pay_data) => {
Self::try_from((item, google_pay_data))
}
- 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::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(
- utils::get_unimplemented_payment_method_error_message("Wellsfargo"),
- )
- .into())
- }
+ 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::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("Wellsfargo"),
+ )
+ .into()),
},
// If connector_mandate_id is present MandatePayment will be the PMD, the case will be handled in the first `if` clause.
// This is a fallback implementation in the event of catastrophe.
- domain::PaymentMethodData::MandatePayment => {
+ PaymentMethodData::MandatePayment => {
let connector_mandate_id =
item.router_data.request.connector_mandate_id().ok_or(
errors::ConnectorError::MissingRequiredField {
@@ -1277,24 +1280,22 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
)?;
Self::try_from((item, connector_mandate_id))
}
- domain::PaymentMethodData::BankDebit(bank_debit) => {
- Self::try_from((item, bank_debit))
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::BankDebit(bank_debit) => Self::try_from((item, bank_debit)),
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | 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("Wellsfargo"),
)
@@ -1306,18 +1307,12 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>>
}
}
-impl
- TryFrom<(
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- )> for WellsfargoPaymentsRequest
+impl TryFrom<(&WellsfargoRouterData<&PaymentsAuthorizeRouterData>, String)>
+ for WellsfargoPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, connector_mandate_id): (
- &WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- ),
+ (item, connector_mandate_id): (&WellsfargoRouterData<&PaymentsAuthorizeRouterData>, String),
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = WellsfargoPaymentInstrument {
@@ -1338,7 +1333,7 @@ impl
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information,
payment_information,
@@ -1367,19 +1362,19 @@ pub struct WellsfargoPaymentsIncrementalAuthorizationRequest {
order_information: OrderInformationIncrementalAuthorization,
}
-impl TryFrom<&WellsfargoRouterData<&types::PaymentsCaptureRouterData>>
+impl TryFrom<&WellsfargoRouterData<&PaymentsCaptureRouterData>>
for WellsfargoPaymentsCaptureRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &WellsfargoRouterData<&types::PaymentsCaptureRouterData>,
+ item: &WellsfargoRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = item
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
processing_information: ProcessingInformation {
capture_options: Some(CaptureOptions {
@@ -1408,12 +1403,12 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsCaptureRouterData>>
}
}
-impl TryFrom<&WellsfargoRouterData<&types::PaymentsIncrementalAuthorizationRouterData>>
+impl TryFrom<&WellsfargoRouterData<&PaymentsIncrementalAuthorizationRouterData>>
for WellsfargoPaymentsIncrementalAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &WellsfargoRouterData<&types::PaymentsIncrementalAuthorizationRouterData>,
+ item: &WellsfargoRouterData<&PaymentsIncrementalAuthorizationRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
processing_information: ProcessingInformation {
@@ -1463,17 +1458,17 @@ pub struct ReversalInformation {
reason: String,
}
-impl TryFrom<&WellsfargoRouterData<&types::PaymentsCancelRouterData>> for WellsfargoVoidRequest {
+impl TryFrom<&WellsfargoRouterData<&PaymentsCancelRouterData>> for WellsfargoVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: &WellsfargoRouterData<&types::PaymentsCancelRouterData>,
+ value: &WellsfargoRouterData<&PaymentsCancelRouterData>,
) -> Result<Self, Self::Error> {
let merchant_defined_information = value
.router_data
.request
.metadata
.clone()
- .map(Vec::<MerchantDefinedInformation>::foreign_from);
+ .map(convert_metadata_to_merchant_defined_info);
Ok(Self {
client_reference_information: ClientReferenceInformation {
code: Some(value.router_data.connector_request_reference_id.clone()),
@@ -1507,10 +1502,10 @@ pub struct WellsfargoAuthType {
pub(super) api_secret: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for WellsfargoAuthType {
+impl TryFrom<&ConnectorAuthType> for WellsfargoAuthType {
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,
@@ -1560,43 +1555,42 @@ pub enum WellsfargoIncrementalAuthorizationStatus {
AuthorizedPendingReview,
}
-impl ForeignFrom<(WellsfargoPaymentStatus, bool)> for enums::AttemptStatus {
- fn foreign_from((status, capture): (WellsfargoPaymentStatus, bool)) -> Self {
- match status {
- WellsfargoPaymentStatus::Authorized
- | WellsfargoPaymentStatus::AuthorizedPendingReview => {
- if capture {
- // Because Wellsfargo will return Payment Status as Authorized even in AutoCapture Payment
- Self::Charged
- } else {
- Self::Authorized
- }
- }
- WellsfargoPaymentStatus::Pending => {
- if capture {
- Self::Charged
- } else {
- Self::Pending
- }
+fn map_attempt_status(status: WellsfargoPaymentStatus, capture: bool) -> enums::AttemptStatus {
+ match status {
+ WellsfargoPaymentStatus::Authorized | WellsfargoPaymentStatus::AuthorizedPendingReview => {
+ if capture {
+ // Because Wellsfargo will return Payment Status as Authorized even in AutoCapture Payment
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Authorized
}
- WellsfargoPaymentStatus::Succeeded | WellsfargoPaymentStatus::Transmitted => {
- Self::Charged
+ }
+ WellsfargoPaymentStatus::Pending => {
+ if capture {
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Pending
}
- WellsfargoPaymentStatus::Voided
- | WellsfargoPaymentStatus::Reversed
- | WellsfargoPaymentStatus::Cancelled => Self::Voided,
- WellsfargoPaymentStatus::Failed
- | WellsfargoPaymentStatus::Declined
- | WellsfargoPaymentStatus::AuthorizedRiskDeclined
- | WellsfargoPaymentStatus::Rejected
- | WellsfargoPaymentStatus::InvalidRequest
- | WellsfargoPaymentStatus::ServerError => Self::Failure,
- WellsfargoPaymentStatus::PendingAuthentication => Self::AuthenticationPending,
- WellsfargoPaymentStatus::PendingReview
- | WellsfargoPaymentStatus::StatusNotReceived
- | WellsfargoPaymentStatus::Challenge
- | WellsfargoPaymentStatus::Accepted => Self::Pending,
}
+ WellsfargoPaymentStatus::Succeeded | WellsfargoPaymentStatus::Transmitted => {
+ enums::AttemptStatus::Charged
+ }
+ WellsfargoPaymentStatus::Voided
+ | WellsfargoPaymentStatus::Reversed
+ | WellsfargoPaymentStatus::Cancelled => enums::AttemptStatus::Voided,
+ WellsfargoPaymentStatus::Failed
+ | WellsfargoPaymentStatus::Declined
+ | WellsfargoPaymentStatus::AuthorizedRiskDeclined
+ | WellsfargoPaymentStatus::Rejected
+ | WellsfargoPaymentStatus::InvalidRequest
+ | WellsfargoPaymentStatus::ServerError => enums::AttemptStatus::Failure,
+ WellsfargoPaymentStatus::PendingAuthentication => {
+ enums::AttemptStatus::AuthenticationPending
+ }
+ WellsfargoPaymentStatus::PendingReview
+ | WellsfargoPaymentStatus::StatusNotReceived
+ | WellsfargoPaymentStatus::Challenge
+ | WellsfargoPaymentStatus::Accepted => enums::AttemptStatus::Pending,
}
}
@@ -1688,84 +1682,17 @@ pub struct WellsfargoErrorInformation {
details: Option<Vec<Details>>,
}
-impl<F, T>
- ForeignFrom<(
- &WellsfargoErrorInformationResponse,
- types::ResponseRouterData<F, WellsfargoPaymentsResponse, T, types::PaymentsResponseData>,
- Option<enums::AttemptStatus>,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
-{
- fn foreign_from(
- (error_response, item, transaction_status): (
- &WellsfargoErrorInformationResponse,
- types::ResponseRouterData<
- F,
- WellsfargoPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
- Option<enums::AttemptStatus>,
- ),
- ) -> Self {
- let detailed_error_info =
- error_response
- .error_information
- .details
- .to_owned()
- .map(|details| {
- details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", ")
- });
-
- let reason = get_error_reason(
- error_response.error_information.message.clone(),
- detailed_error_info,
- None,
- );
- let response = Err(types::ErrorResponse {
- code: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_response
- .error_information
- .reason
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code: item.http_code,
- attempt_status: None,
- connector_transaction_id: Some(error_response.id.clone()),
- });
- match transaction_status {
- Some(status) => Self {
- response,
- status,
- ..item.data
- },
- None => Self {
- response,
- ..item.data
- },
- }
- }
-}
-
fn get_error_response_if_failure(
(info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16),
-) -> Option<types::ErrorResponse> {
+) -> Option<ErrorResponse> {
if utils::is_payment_failure(status) {
- Some(types::ErrorResponse::foreign_from((
+ Some(get_error_response(
&info_response.error_information,
&info_response.risk_information,
Some(status),
http_code,
info_response.id.clone(),
- )))
+ ))
} else {
None
}
@@ -1773,7 +1700,7 @@ fn get_error_response_if_failure(
fn get_payment_response(
(info_response, status, http_code): (&WellsfargoPaymentsResponse, enums::AttemptStatus, u16),
-) -> Result<types::PaymentsResponseData, types::ErrorResponse> {
+) -> Result<PaymentsResponseData, ErrorResponse> {
let error_response = get_error_response_if_failure((info_response, status, http_code));
match error_response {
Some(error) => Err(error),
@@ -1784,7 +1711,7 @@ fn get_payment_response(
info_response
.token_information
.clone()
- .map(|token_info| types::MandateReference {
+ .map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
@@ -1793,8 +1720,8 @@ fn get_payment_response(
connector_mandate_request_reference_id: None,
});
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(info_response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -1817,38 +1744,37 @@ fn get_payment_response(
impl
TryFrom<
- types::ResponseRouterData<
- api::Authorize,
+ ResponseRouterData<
+ Authorize,
WellsfargoPaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
- >
- for types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- api::Authorize,
+ item: ResponseRouterData<
+ Authorize,
WellsfargoPaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
+ PaymentsAuthorizeData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_attempt_status(
item.response
.status
.clone()
.unwrap_or(WellsfargoPaymentStatus::StatusNotReceived),
item.data.request.is_auto_capture()?,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
let connector_response = item
.response
.processor_information
.as_ref()
- .map(types::AdditionalPaymentMethodConnectorResponse::from)
- .map(types::ConnectorResponseData::with_additional_payment_method_data);
+ .map(AdditionalPaymentMethodConnectorResponse::from)
+ .map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status,
@@ -1859,7 +1785,7 @@ impl
}
}
-impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnectorResponse {
+impl From<&ClientProcessorInformation> for AdditionalPaymentMethodConnectorResponse {
fn from(processor_information: &ClientProcessorInformation) -> Self {
let payment_checks = Some(
serde_json::json!({"avs_response": processor_information.avs, "card_verification": processor_information.card_verification}),
@@ -1874,30 +1800,30 @@ impl From<&ClientProcessorInformation> for types::AdditionalPaymentMethodConnect
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
WellsfargoPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
WellsfargoPaymentsResponse,
- types::PaymentsCaptureData,
- types::PaymentsResponseData,
+ PaymentsCaptureData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_attempt_status(
item.response
.status
.clone()
.unwrap_or(WellsfargoPaymentStatus::StatusNotReceived),
true,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
Ok(Self {
status,
@@ -1909,30 +1835,25 @@ impl<F>
impl<F>
TryFrom<
- types::ResponseRouterData<
- F,
- WellsfargoPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>
+ ResponseRouterData<F, WellsfargoPaymentsResponse, PaymentsCancelData, PaymentsResponseData>,
+ > for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
WellsfargoPaymentsResponse,
- types::PaymentsCancelData,
- types::PaymentsResponseData,
+ PaymentsCancelData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let status = enums::AttemptStatus::foreign_from((
+ let status = map_attempt_status(
item.response
.status
.clone()
.unwrap_or(WellsfargoPaymentStatus::StatusNotReceived),
false,
- ));
+ );
let response = get_payment_response((&item.response, status, item.http_code));
Ok(Self {
status,
@@ -1945,33 +1866,28 @@ impl<F>
// zero dollar response
impl
TryFrom<
- types::ResponseRouterData<
- api::SetupMandate,
+ ResponseRouterData<
+ SetupMandate,
WellsfargoPaymentsResponse,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
+ SetupMandateRequestData,
+ PaymentsResponseData,
>,
- >
- for types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >
+ > for RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- api::SetupMandate,
+ item: ResponseRouterData<
+ SetupMandate,
WellsfargoPaymentsResponse,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
+ SetupMandateRequestData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let mandate_reference =
item.response
.token_information
.clone()
- .map(|token_info| types::MandateReference {
+ .map(|token_info| MandateReference {
connector_mandate_id: token_info
.payment_instrument
.map(|payment_instrument| payment_instrument.id.expose()),
@@ -1979,13 +1895,13 @@ impl
mandate_metadata: None,
connector_mandate_request_reference_id: None,
});
- let mut mandate_status = enums::AttemptStatus::foreign_from((
+ let mut mandate_status = map_attempt_status(
item.response
.status
.clone()
.unwrap_or(WellsfargoPaymentStatus::StatusNotReceived),
false,
- ));
+ );
if matches!(mandate_status, enums::AttemptStatus::Authorized) {
//In case of zero auth mandates we want to make the payment reach the terminal status so we are converting the authorized status to charged as well.
mandate_status = enums::AttemptStatus::Charged
@@ -1997,17 +1913,15 @@ impl
.response
.processor_information
.as_ref()
- .map(types::AdditionalPaymentMethodConnectorResponse::from)
- .map(types::ConnectorResponseData::with_additional_payment_method_data);
+ .map(AdditionalPaymentMethodConnectorResponse::from)
+ .map(ConnectorResponseData::with_additional_payment_method_data);
Ok(Self {
status: mandate_status,
response: match error_response {
Some(error) => Err(error),
- None => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.id.clone(),
- ),
+ None => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -2037,47 +1951,38 @@ impl
}
impl<F, T>
- ForeignTryFrom<(
- types::ResponseRouterData<
+ TryFrom<
+ ResponseRouterData<
F,
WellsfargoPaymentsIncrementalAuthorizationResponse,
T,
- types::PaymentsResponseData,
+ PaymentsResponseData,
>,
- bool,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ > for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn foreign_try_from(
- data: (
- types::ResponseRouterData<
- F,
- WellsfargoPaymentsIncrementalAuthorizationResponse,
- T,
- types::PaymentsResponseData,
- >,
- bool,
- ),
+ fn try_from(
+ item: ResponseRouterData<
+ F,
+ WellsfargoPaymentsIncrementalAuthorizationResponse,
+ T,
+ PaymentsResponseData,
+ >,
) -> Result<Self, Self::Error> {
- let item = data.0;
Ok(Self {
response: match item.response.error_information {
- Some(error) => Ok(
- types::PaymentsResponseData::IncrementalAuthorizationResponse {
- status: common_enums::AuthorizationStatus::Failure,
- error_code: error.reason,
- error_message: error.message,
- connector_authorization_id: None,
- },
- ),
- _ => Ok(
- types::PaymentsResponseData::IncrementalAuthorizationResponse {
- status: item.response.status.into(),
- error_code: None,
- error_message: None,
- connector_authorization_id: None,
- },
- ),
+ Some(error) => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
+ status: common_enums::AuthorizationStatus::Failure,
+ error_code: error.reason,
+ error_message: error.message,
+ connector_authorization_id: None,
+ }),
+ _ => Ok(PaymentsResponseData::IncrementalAuthorizationResponse {
+ status: item.response.status.into(),
+ error_code: None,
+ error_message: None,
+ connector_authorization_id: None,
+ }),
},
..item.data
})
@@ -2101,49 +2006,46 @@ pub struct ApplicationInformation {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
WellsfargoTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
WellsfargoTransactionResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
+ PaymentsSyncData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.application_information.status {
Some(status) => {
- let status = enums::AttemptStatus::foreign_from((
- status,
- item.data.request.is_auto_capture()?,
- ));
+ let status = map_attempt_status(status, item.data.request.is_auto_capture()?);
let incremental_authorization_allowed =
Some(status == enums::AttemptStatus::Authorized);
let risk_info: Option<ClientRiskInformation> = None;
if utils::is_payment_failure(status) {
Ok(Self {
- response: Err(types::ErrorResponse::foreign_from((
+ response: Err(get_error_response(
&item.response.error_information,
&risk_info,
Some(status),
item.http_code,
item.response.id.clone(),
- ))),
+ )),
status: enums::AttemptStatus::Failure,
..item.data
})
} else {
Ok(Self {
status,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
redirection_data: Box::new(None),
@@ -2164,10 +2066,8 @@ impl<F>
}
None => Ok(Self {
status: item.data.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: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -2189,11 +2089,9 @@ pub struct WellsfargoRefundRequest {
client_reference_information: ClientReferenceInformation,
}
-impl<F> TryFrom<&WellsfargoRouterData<&types::RefundsRouterData<F>>> for WellsfargoRefundRequest {
+impl<F> TryFrom<&WellsfargoRouterData<&RefundsRouterData<F>>> for WellsfargoRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &WellsfargoRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &WellsfargoRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
order_information: OrderInformation {
amount_details: Amount {
@@ -2241,24 +2139,24 @@ pub struct WellsfargoRefundResponse {
error_information: Option<WellsfargoErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, WellsfargoRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, WellsfargoRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, WellsfargoRefundResponse>,
+ item: RefundsResponseRouterData<Execute, WellsfargoRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response.status.clone());
let response = if utils::is_refund_failure(refund_status) {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status: enums::RefundStatus::from(item.response.status),
})
@@ -2285,12 +2183,12 @@ pub struct WellsfargoRsyncResponse {
error_information: Option<WellsfargoErrorInformation>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, WellsfargoRsyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, WellsfargoRsyncResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, WellsfargoRsyncResponse>,
+ item: RefundsResponseRouterData<RSync, WellsfargoRsyncResponse>,
) -> Result<Self, Self::Error> {
let response = match item
.response
@@ -2301,35 +2199,35 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, WellsfargoRsyncRespons
let refund_status = enums::RefundStatus::from(status.clone());
if utils::is_refund_failure(refund_status) {
if status == WellsfargoRefundStatus::Voided {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&Some(WellsfargoErrorInformation {
- message: Some(consts::REFUND_VOIDED.to_string()),
- reason: Some(consts::REFUND_VOIDED.to_string()),
+ message: Some(constants::REFUND_VOIDED.to_string()),
+ reason: Some(constants::REFUND_VOIDED.to_string()),
details: None,
}),
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
} else {
- Err(types::ErrorResponse::foreign_from((
+ Err(get_error_response(
&item.response.error_information,
&None,
None,
item.http_code,
item.response.id.clone(),
- )))
+ ))
}
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
})
}
}
- None => Ok(types::RefundsResponseData {
+ None => Ok(RefundsResponseData {
connector_refund_id: item.response.id.clone(),
refund_status: match item.data.response {
Ok(response) => response.refund_status,
@@ -2418,73 +2316,60 @@ pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
-impl
- ForeignFrom<(
- &Option<WellsfargoErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- )> for types::ErrorResponse
-{
- fn foreign_from(
- (error_data, risk_information, attempt_status, status_code, transaction_id): (
- &Option<WellsfargoErrorInformation>,
- &Option<ClientRiskInformation>,
- Option<enums::AttemptStatus>,
- u16,
- String,
- ),
- ) -> Self {
- let avs_message = risk_information
- .clone()
- .map(|client_risk_information| {
- client_risk_information.rules.map(|rules| {
- rules
- .iter()
- .map(|risk_info| {
- risk_info.name.clone().map_or("".to_string(), |name| {
- format!(" , {}", name.clone().expose())
- })
+pub fn get_error_response(
+ error_data: &Option<WellsfargoErrorInformation>,
+ risk_information: &Option<ClientRiskInformation>,
+ attempt_status: Option<enums::AttemptStatus>,
+ status_code: u16,
+ transaction_id: String,
+) -> ErrorResponse {
+ let avs_message = risk_information
+ .clone()
+ .map(|client_risk_information| {
+ client_risk_information.rules.map(|rules| {
+ rules
+ .iter()
+ .map(|risk_info| {
+ risk_info.name.clone().map_or("".to_string(), |name| {
+ format!(" , {}", name.clone().expose())
})
- .collect::<Vec<String>>()
- .join("")
- })
+ })
+ .collect::<Vec<String>>()
+ .join("")
})
- .unwrap_or(Some("".to_string()));
+ })
+ .unwrap_or(Some("".to_string()));
+
+ let detailed_error_info = error_data
+ .clone()
+ .map(|error_data| match error_data.details {
+ Some(details) => details
+ .iter()
+ .map(|details| format!("{} : {}", details.field, details.reason))
+ .collect::<Vec<_>>()
+ .join(", "),
+ None => "".to_string(),
+ });
- let detailed_error_info = error_data
+ let reason = get_error_reason(
+ error_data.clone().and_then(|error_info| error_info.message),
+ detailed_error_info,
+ avs_message,
+ );
+ let error_message = error_data.clone().and_then(|error_info| error_info.reason);
+ ErrorResponse {
+ code: error_message
.clone()
- .map(|error_data| match error_data.details {
- Some(details) => details
- .iter()
- .map(|details| format!("{} : {}", details.field, details.reason))
- .collect::<Vec<_>>()
- .join(", "),
- None => "".to_string(),
- });
-
- let reason = get_error_reason(
- error_data.clone().and_then(|error_info| error_info.message),
- detailed_error_info,
- avs_message,
- );
- let error_message = error_data.clone().and_then(|error_info| error_info.reason);
- Self {
- code: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: error_message
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason,
- status_code,
- attempt_status,
- connector_transaction_id: Some(transaction_id.clone()),
- }
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
+ message: error_message
+ .clone()
+ .unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
+ reason,
+ status_code,
+ attempt_status,
+ connector_transaction_id: Some(transaction_id.clone()),
}
}
-
pub fn get_error_reason(
error_info: Option<String>,
detailed_error_info: Option<String>,
diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs
index 3d99f8d167f..e83438d325b 100644
--- a/crates/hyperswitch_connectors/src/constants.rs
+++ b/crates/hyperswitch_connectors/src/constants.rs
@@ -32,3 +32,11 @@ pub(crate) mod headers {
/// Unsupported response type error message
pub const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
+
+/// Error message for Authentication Error from the connector
+pub const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector";
+
+/// Error message when Refund request has been voided.
+pub const REFUND_VOIDED: &str = "Refund request has been voided.";
+
+pub const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method";
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 0e752a29373..a2db7ad7b6e 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -99,6 +99,7 @@ default_imp_for_authorize_session_token!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -106,6 +107,7 @@ default_imp_for_authorize_session_token!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -144,6 +146,7 @@ default_imp_for_authorize_session_token!(
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
@@ -169,6 +172,7 @@ default_imp_for_calculate_tax!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -176,6 +180,7 @@ default_imp_for_calculate_tax!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -214,6 +219,7 @@ default_imp_for_calculate_tax!(
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
@@ -239,6 +245,7 @@ default_imp_for_session_update!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -246,6 +253,7 @@ default_imp_for_session_update!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Digitalvirgo,
connectors::Dlocal,
@@ -279,6 +287,7 @@ default_imp_for_session_update!(
connectors::Gocardless,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
@@ -310,6 +319,7 @@ default_imp_for_post_session_tokens!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Bitpay,
connectors::Bluesnap,
connectors::Boku,
@@ -317,6 +327,7 @@ default_imp_for_post_session_tokens!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Digitalvirgo,
connectors::Dlocal,
@@ -349,6 +360,7 @@ default_imp_for_post_session_tokens!(
connectors::Gocardless,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Powertranz,
connectors::Prophetpay,
@@ -381,6 +393,7 @@ macro_rules! default_imp_for_complete_authorize {
default_imp_for_complete_authorize!(
connectors::Amazonpay,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Boku,
@@ -415,6 +428,7 @@ default_imp_for_complete_authorize!(
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Xendit,
@@ -443,6 +457,7 @@ default_imp_for_incremental_authorization!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -515,6 +530,7 @@ default_imp_for_create_customer!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -522,6 +538,7 @@ default_imp_for_create_customer!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -558,6 +575,7 @@ default_imp_for_create_customer!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -588,9 +606,11 @@ default_imp_for_connector_redirect_response!(
connectors::Bitpay,
connectors::Boku,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Dlocal,
@@ -623,6 +643,7 @@ default_imp_for_connector_redirect_response!(
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Zsl,
@@ -648,6 +669,7 @@ default_imp_for_pre_processing_steps!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -690,6 +712,7 @@ default_imp_for_pre_processing_steps!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -717,6 +740,7 @@ default_imp_for_post_processing_steps!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -724,6 +748,7 @@ default_imp_for_post_processing_steps!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -762,6 +787,7 @@ default_imp_for_post_processing_steps!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -789,6 +815,7 @@ default_imp_for_approve!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -796,6 +823,7 @@ default_imp_for_approve!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -834,6 +862,7 @@ default_imp_for_approve!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -861,6 +890,7 @@ default_imp_for_reject!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -868,6 +898,7 @@ default_imp_for_reject!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -906,6 +937,7 @@ default_imp_for_reject!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -933,6 +965,7 @@ default_imp_for_webhook_source_verification!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -940,6 +973,7 @@ default_imp_for_webhook_source_verification!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -978,6 +1012,7 @@ default_imp_for_webhook_source_verification!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1006,6 +1041,7 @@ default_imp_for_accept_dispute!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1013,6 +1049,7 @@ default_imp_for_accept_dispute!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1051,6 +1088,7 @@ default_imp_for_accept_dispute!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1078,6 +1116,7 @@ default_imp_for_submit_evidence!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1085,6 +1124,7 @@ default_imp_for_submit_evidence!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1123,6 +1163,7 @@ default_imp_for_submit_evidence!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1150,6 +1191,7 @@ default_imp_for_defend_dispute!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1157,6 +1199,7 @@ default_imp_for_defend_dispute!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1195,6 +1238,7 @@ default_imp_for_defend_dispute!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1231,6 +1275,7 @@ default_imp_for_file_upload!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1238,6 +1283,7 @@ default_imp_for_file_upload!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1276,6 +1322,7 @@ default_imp_for_file_upload!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1296,6 +1343,7 @@ default_imp_for_payouts!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1341,6 +1389,7 @@ default_imp_for_payouts!(
connectors::Volt,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl,
@@ -1369,6 +1418,7 @@ default_imp_for_payouts_create!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1376,6 +1426,7 @@ default_imp_for_payouts_create!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1414,6 +1465,7 @@ default_imp_for_payouts_create!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1443,6 +1495,7 @@ default_imp_for_payouts_retrieve!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1450,6 +1503,7 @@ default_imp_for_payouts_retrieve!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1488,6 +1542,7 @@ default_imp_for_payouts_retrieve!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1517,6 +1572,7 @@ default_imp_for_payouts_eligibility!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1524,6 +1580,7 @@ default_imp_for_payouts_eligibility!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1562,6 +1619,7 @@ default_imp_for_payouts_eligibility!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1591,6 +1649,7 @@ default_imp_for_payouts_fulfill!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1636,6 +1695,7 @@ default_imp_for_payouts_fulfill!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1665,6 +1725,7 @@ default_imp_for_payouts_cancel!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1672,6 +1733,7 @@ default_imp_for_payouts_cancel!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1710,6 +1772,7 @@ default_imp_for_payouts_cancel!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1739,6 +1802,7 @@ default_imp_for_payouts_quote!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1746,6 +1810,7 @@ default_imp_for_payouts_quote!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1784,6 +1849,7 @@ default_imp_for_payouts_quote!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1813,6 +1879,7 @@ default_imp_for_payouts_recipient!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1820,6 +1887,7 @@ default_imp_for_payouts_recipient!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1858,6 +1926,7 @@ default_imp_for_payouts_recipient!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1887,6 +1956,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1894,6 +1964,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1932,6 +2003,7 @@ default_imp_for_payouts_recipient_account!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -1961,6 +2033,7 @@ default_imp_for_frm_sale!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1968,6 +2041,7 @@ default_imp_for_frm_sale!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2006,6 +2080,7 @@ default_imp_for_frm_sale!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2035,6 +2110,7 @@ default_imp_for_frm_checkout!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2042,6 +2118,7 @@ default_imp_for_frm_checkout!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2080,6 +2157,7 @@ default_imp_for_frm_checkout!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2109,6 +2187,7 @@ default_imp_for_frm_transaction!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2116,6 +2195,7 @@ default_imp_for_frm_transaction!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2154,6 +2234,7 @@ default_imp_for_frm_transaction!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2183,6 +2264,7 @@ default_imp_for_frm_fulfillment!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2190,6 +2272,7 @@ default_imp_for_frm_fulfillment!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2228,6 +2311,7 @@ default_imp_for_frm_fulfillment!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2257,6 +2341,7 @@ default_imp_for_frm_record_return!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2264,6 +2349,7 @@ default_imp_for_frm_record_return!(
connectors::Cashtocode,
connectors::Coinbase,
connectors::Cryptopay,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2302,6 +2388,7 @@ default_imp_for_frm_record_return!(
connectors::UnifiedAuthenticationService,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2328,6 +2415,7 @@ default_imp_for_revoking_mandates!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2400,6 +2488,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bluesnap,
connectors::Bitpay,
@@ -2408,6 +2497,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2445,6 +2535,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
@@ -2470,6 +2561,7 @@ default_imp_for_uas_post_authentication!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -2478,6 +2570,7 @@ default_imp_for_uas_post_authentication!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -2515,6 +2608,7 @@ default_imp_for_uas_post_authentication!(
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Volt,
connectors::Xendit,
connectors::Zen,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 4161b36f906..485ff86d728 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -209,6 +209,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -217,6 +218,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -256,6 +258,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -282,6 +285,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -290,6 +294,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -326,6 +331,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Thunes,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
+ connectors::Wellsfargo,
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
@@ -350,6 +356,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -358,6 +365,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -397,6 +405,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -424,6 +433,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -471,6 +481,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -497,6 +508,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -544,6 +556,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -570,6 +583,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -578,6 +592,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -617,6 +632,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -653,6 +669,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -661,6 +678,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -700,6 +718,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -728,6 +747,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -736,6 +756,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -775,6 +796,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -803,6 +825,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -811,6 +834,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -850,6 +874,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -878,6 +903,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -886,6 +912,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -925,6 +952,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -953,6 +981,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -961,6 +990,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1000,6 +1030,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1028,6 +1059,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1036,6 +1068,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1075,6 +1108,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1103,6 +1137,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1111,6 +1146,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1150,6 +1186,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1178,6 +1215,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1186,6 +1224,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1225,6 +1264,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1253,6 +1293,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1261,6 +1302,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1300,6 +1342,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1326,6 +1369,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1334,6 +1378,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1373,6 +1418,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1401,6 +1447,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1409,6 +1456,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1448,6 +1496,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1476,6 +1525,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1484,6 +1534,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1523,6 +1574,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1551,6 +1603,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1559,6 +1612,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1598,6 +1652,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1626,6 +1681,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1634,6 +1690,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1673,6 +1730,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1701,6 +1759,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1709,6 +1768,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1748,6 +1808,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
@@ -1773,6 +1834,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Amazonpay,
connectors::Bambora,
connectors::Bamboraapac,
+ connectors::Bankofamerica,
connectors::Billwerk,
connectors::Bitpay,
connectors::Bluesnap,
@@ -1781,6 +1843,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Coinbase,
connectors::Cryptopay,
connectors::CtpMastercard,
+ connectors::Cybersource,
connectors::Datatrans,
connectors::Deutschebank,
connectors::Digitalvirgo,
@@ -1820,6 +1883,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Worldline,
connectors::Volt,
connectors::Worldpay,
+ connectors::Wellsfargo,
connectors::Xendit,
connectors::Zen,
connectors::Zsl
diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs
index 05ef62d7828..f731450f386 100644
--- a/crates/hyperswitch_connectors/src/types.rs
+++ b/crates/hyperswitch_connectors/src/types.rs
@@ -1,3 +1,5 @@
+#[cfg(feature = "payouts")]
+use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData};
use hyperswitch_domain_models::{
router_data::{AccessToken, RouterData},
router_flow_types::{AccessTokenAuth, Capture, PSync, PreProcessing, Session, Void},
@@ -25,6 +27,10 @@ pub(crate) type PaymentsPreprocessingResponseRouterData<R> =
pub(crate) type PaymentsSessionResponseRouterData<R> =
ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>;
+#[cfg(feature = "payouts")]
+pub type PayoutsResponseRouterData<F, R> =
+ ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
+
// TODO: Remove `ResponseRouterData` from router crate after all the related type aliases are moved to this crate.
pub struct ResponseRouterData<Flow, R, Request, Response> {
pub response: R,
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 671aed36378..e99777ad27e 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -1,6 +1,8 @@
use std::collections::{HashMap, HashSet};
use api_models::payments;
+#[cfg(feature = "payouts")]
+use api_models::payouts::PayoutVendorAccountDetails;
use base64::Engine;
use common_enums::{
enums,
@@ -23,9 +25,9 @@ use hyperswitch_domain_models::{
},
router_request_types::{
AuthenticationData, BrowserInformation, CompleteAuthorizeData, ConnectorCustomerData,
- PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
- PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, RefundsData, ResponseId,
- SetupMandateRequestData,
+ MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData,
+ RefundsData, ResponseId, SetupMandateRequestData,
},
types::OrderDetailsWithAmount,
};
@@ -1375,6 +1377,8 @@ pub trait PaymentsAuthorizeRequestData {
&self,
) -> Result<Secret<String>, Error>;
fn is_cit_mandate_payment(&self) -> bool;
+ fn get_optional_network_transaction_id(&self) -> Option<String>;
+ fn get_optional_email(&self) -> Option<Email>;
}
impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
@@ -1564,6 +1568,21 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
+ fn get_optional_network_transaction_id(&self) -> Option<String> {
+ self.mandate_id
+ .as_ref()
+ .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
+ Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
+ Some(network_transaction_id.clone())
+ }
+ Some(payments::MandateReferenceId::ConnectorMandateId(_))
+ | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_))
+ | None => None,
+ })
+ }
+ fn get_optional_email(&self) -> Option<Email> {
+ self.email.clone()
+ }
}
pub trait PaymentsCaptureRequestData {
@@ -1816,12 +1835,41 @@ impl AddressData for Address {
}
}
pub trait PaymentsPreProcessingRequestData {
- fn get_amount(&self) -> Result<i64, Error>;
+ fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
+ fn get_email(&self) -> Result<Email, Error>;
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
+ fn get_amount(&self) -> Result<i64, Error>;
+ fn get_minor_amount(&self) -> Result<MinorUnit, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
+ fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
+ fn get_webhook_url(&self) -> Result<String, Error>;
+ fn get_router_return_url(&self) -> Result<String, Error>;
+ fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
+ fn get_complete_authorize_url(&self) -> Result<String, Error>;
+ fn connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData {
+ fn get_email(&self) -> Result<Email, Error> {
+ self.email.clone().ok_or_else(missing_field_err("email"))
+ }
+ fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
+ self.payment_method_type
+ .to_owned()
+ .ok_or_else(missing_field_err("payment_method_type"))
+ }
+ fn get_currency(&self) -> Result<enums::Currency, Error> {
+ self.currency.ok_or_else(missing_field_err("currency"))
+ }
+ fn get_amount(&self) -> Result<i64, Error> {
+ self.amount.ok_or_else(missing_field_err("amount"))
+ }
+
+ // New minor amount function for amount framework
+ fn get_minor_amount(&self) -> Result<MinorUnit, Error> {
+ self.minor_amount.ok_or_else(missing_field_err("amount"))
+ }
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
@@ -1833,11 +1881,53 @@ impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData {
}
}
}
- fn get_amount(&self) -> Result<i64, Error> {
- self.amount.ok_or_else(missing_field_err("amount"))
+ fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
+ self.order_details
+ .clone()
+ .ok_or_else(missing_field_err("order_details"))
}
- fn get_currency(&self) -> Result<enums::Currency, Error> {
- self.currency.ok_or_else(missing_field_err("currency"))
+ fn get_webhook_url(&self) -> Result<String, Error> {
+ self.webhook_url
+ .clone()
+ .ok_or_else(missing_field_err("webhook_url"))
+ }
+ fn get_router_return_url(&self) -> Result<String, Error> {
+ self.router_return_url
+ .clone()
+ .ok_or_else(missing_field_err("return_url"))
+ }
+ fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
+ self.browser_info
+ .clone()
+ .ok_or_else(missing_field_err("browser_info"))
+ }
+ fn get_complete_authorize_url(&self) -> Result<String, Error> {
+ self.complete_authorize_url
+ .clone()
+ .ok_or_else(missing_field_err("complete_authorize_url"))
+ }
+ fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
+ self.redirect_response
+ .as_ref()
+ .and_then(|res| res.payload.to_owned())
+ .ok_or(
+ errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "request.redirect_response.payload",
+ }
+ .into(),
+ )
+ }
+ fn connector_mandate_id(&self) -> Option<String> {
+ self.mandate_id
+ .as_ref()
+ .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
+ Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
+ connector_mandate_ids.get_connector_mandate_id()
+ }
+ Some(payments::MandateReferenceId::NetworkMandateId(_))
+ | None
+ | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
+ })
}
}
@@ -2544,3 +2634,180 @@ pub fn deserialize_xml_to_struct<T: serde::de::DeserializeOwned>(
Ok(result)
}
+
+#[cfg(feature = "payouts")]
+pub trait PayoutsData {
+ fn get_transfer_id(&self) -> Result<String, Error>;
+ fn get_customer_details(
+ &self,
+ ) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>;
+ fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
+ #[cfg(feature = "payouts")]
+ fn get_payout_type(&self) -> Result<enums::PayoutType, Error>;
+}
+
+#[cfg(feature = "payouts")]
+impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsData {
+ fn get_transfer_id(&self) -> Result<String, Error> {
+ self.connector_payout_id
+ .clone()
+ .ok_or_else(missing_field_err("transfer_id"))
+ }
+ fn get_customer_details(
+ &self,
+ ) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error> {
+ self.customer_details
+ .clone()
+ .ok_or_else(missing_field_err("customer_details"))
+ }
+ fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> {
+ self.vendor_details
+ .clone()
+ .ok_or_else(missing_field_err("vendor_details"))
+ }
+ #[cfg(feature = "payouts")]
+ fn get_payout_type(&self) -> Result<enums::PayoutType, Error> {
+ self.payout_type
+ .to_owned()
+ .ok_or_else(missing_field_err("payout_type"))
+ }
+}
+pub trait RevokeMandateRequestData {
+ fn get_connector_mandate_id(&self) -> Result<String, Error>;
+}
+
+impl RevokeMandateRequestData for MandateRevokeRequestData {
+ fn get_connector_mandate_id(&self) -> Result<String, Error> {
+ self.connector_mandate_id
+ .clone()
+ .ok_or_else(missing_field_err("connector_mandate_id"))
+ }
+}
+pub trait RecurringMandateData {
+ fn get_original_payment_amount(&self) -> Result<i64, Error>;
+ fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
+}
+
+impl RecurringMandateData for RecurringMandatePaymentData {
+ fn get_original_payment_amount(&self) -> Result<i64, Error> {
+ self.original_payment_authorized_amount
+ .ok_or_else(missing_field_err("original_payment_authorized_amount"))
+ }
+ fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
+ self.original_payment_authorized_currency
+ .ok_or_else(missing_field_err("original_payment_authorized_currency"))
+ }
+}
+
+#[cfg(feature = "payouts")]
+impl CardData for api_models::payouts::CardPayout {
+ fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let binding = self.expiry_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.expiry_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.expiry_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.expiry_month.peek(),
+ delimiter,
+ year.peek()
+ ))
+ }
+ fn get_expiry_year_4_digit(&self) -> Secret<String> {
+ let mut year = self.expiry_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.expiry_month.clone().expose();
+ Ok(Secret::new(format!("{year}{month}")))
+ }
+ fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
+ self.expiry_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.expiry_year
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+
+ fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
+ let year = self.get_card_expiry_year_2_digit()?.expose();
+ let month = self.expiry_month.clone().expose();
+ Ok(Secret::new(format!("{month}{year}")))
+ }
+
+ fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
+ self.get_expiry_year_4_digit()
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
+ self.card_holder_name
+ .clone()
+ .ok_or_else(missing_field_err("card.card_holder_name"))
+ }
+}
+
+pub trait NetworkTokenData {
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
+ fn get_expiry_year_4_digit(&self) -> Secret<String>;
+}
+
+impl NetworkTokenData for payment_method_data::NetworkTokenData {
+ fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
+ get_card_issuer(self.token_number.peek())
+ }
+
+ fn get_expiry_year_4_digit(&self) -> Secret<String> {
+ let mut year = self.token_exp_year.peek().clone();
+ if year.len() == 2 {
+ year = format!("20{}", year);
+ }
+ Secret::new(year)
+ }
+}
diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs
index 2dd38d88b6d..4bbab24edfe 100644
--- a/crates/hyperswitch_domain_models/src/types.rs
+++ b/crates/hyperswitch_domain_models/src/types.rs
@@ -3,10 +3,10 @@ pub use diesel_models::types::OrderDetailsWithAmount;
use crate::{
router_data::{AccessToken, RouterData},
router_flow_types::{
- AccessTokenAuth, Authorize, AuthorizeSessionToken, CalculateTax, Capture,
- CompleteAuthorize, CreateConnectorCustomer, Execute, PSync, PaymentMethodToken,
- PostAuthenticate, PostSessionTokens, PreAuthenticate, PreProcessing, RSync, Session,
- SetupMandate, Void,
+ mandate_revoke::MandateRevoke, AccessTokenAuth, Authorize, AuthorizeSessionToken,
+ CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, Execute,
+ IncrementalAuthorization, PSync, PaymentMethodToken, PostAuthenticate, PostSessionTokens,
+ PreAuthenticate, PreProcessing, RSync, Session, SetupMandate, Void,
},
router_request_types::{
unified_authentication_service::{
@@ -14,15 +14,19 @@ use crate::{
UasPreAuthenticationRequestData,
},
AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
- ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
- PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData,
+ ConnectorCustomerData, MandateRevokeRequestData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
PaymentsTaxCalculationData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
- PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData,
+ MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData,
+ TaxCalculationResponseData,
},
};
+#[cfg(feature = "payouts")]
+pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData};
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
@@ -56,3 +60,14 @@ pub type UasPostAuthenticationRouterData =
pub type UasPreAuthenticationRouterData =
RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>;
+
+pub type MandateRevokeRouterData =
+ RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
+pub type PaymentsIncrementalAuthorizationRouterData = RouterData<
+ IncrementalAuthorization,
+ PaymentsIncrementalAuthorizationData,
+ PaymentsResponseData,
+>;
+
+#[cfg(feature = "payouts")]
+pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 0da0e711fbc..0bd9190f11c 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -2,10 +2,8 @@ pub mod aci;
pub mod adyen;
pub mod adyenplatform;
pub mod authorizedotnet;
-pub mod bankofamerica;
pub mod braintree;
pub mod checkout;
-pub mod cybersource;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
@@ -31,16 +29,16 @@ pub mod stripe;
pub mod threedsecureio;
pub mod trustpay;
pub mod utils;
-pub mod wellsfargo;
pub mod wellsfargopayout;
pub mod wise;
pub use hyperswitch_connectors::connectors::{
airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, bambora, bambora::Bambora,
- bamboraapac, bamboraapac::Bamboraapac, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay,
- bluesnap, bluesnap::Bluesnap, boku, boku::Boku, cashtocode, cashtocode::Cashtocode, coinbase,
- coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, ctp_mastercard,
- ctp_mastercard::CtpMastercard, datatrans, datatrans::Datatrans, deutschebank,
+ bamboraapac, bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, billwerk,
+ billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, bluesnap::Bluesnap, boku, boku::Boku,
+ cashtocode, cashtocode::Cashtocode, coinbase, coinbase::Coinbase, cryptopay,
+ cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource,
+ cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank,
deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal,
elavon, elavon::Elavon, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu,
fiuu::Fiuu, forte, forte::Forte, globepay, globepay::Globepay, gocardless,
@@ -52,20 +50,19 @@ pub use hyperswitch_connectors::connectors::{
prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, redsys,
redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar,
taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, unified_authentication_service,
- unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, worldline,
- worldline::Worldline, worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl,
- zsl::Zsl,
+ unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo,
+ wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit,
+ xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl,
};
#[cfg(feature = "dummy_connector")]
pub use self::dummyconnector::DummyConnector;
pub use self::{
aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, authorizedotnet::Authorizedotnet,
- bankofamerica::Bankofamerica, braintree::Braintree, checkout::Checkout,
- cybersource::Cybersource, ebanx::Ebanx, globalpay::Globalpay, gpayments::Gpayments,
- iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, netcetera::Netcetera,
- nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payme::Payme,
- payone::Payone, paypal::Paypal, plaid::Plaid, riskified::Riskified, signifyd::Signifyd,
- stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargo::Wellsfargo,
+ braintree::Braintree, checkout::Checkout, ebanx::Ebanx, globalpay::Globalpay,
+ gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity,
+ netcetera::Netcetera, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode,
+ payme::Payme, payone::Payone, paypal::Paypal, plaid::Plaid, riskified::Riskified,
+ signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay,
wellsfargopayout::Wellsfargopayout, wise::Wise,
};
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 038da0be41c..9e00bcd6bce 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -41,7 +41,6 @@ pub const DEFAULT_LIST_API_LIMIT: u16 = 10;
pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
pub(crate) const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method";
pub(crate) const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector";
-pub(crate) const REFUND_VOIDED: &str = "Refund request has been voided.";
pub(crate) const CANNOT_CONTINUE_AUTH: &str =
"Cannot continue with Authorization due to failed Liability Shift.";
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 697ec6fbdf1..28febe8b0b6 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -699,10 +699,8 @@ default_imp_for_new_connector_integration_payment!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -724,7 +722,6 @@ default_imp_for_new_connector_integration_payment!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
connector::Plaid
@@ -751,10 +748,8 @@ default_imp_for_new_connector_integration_refund!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -776,7 +771,6 @@ default_imp_for_new_connector_integration_refund!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -797,10 +791,8 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -822,7 +814,6 @@ default_imp_for_new_connector_integration_connector_access_token!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -865,10 +856,8 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -890,7 +879,6 @@ default_imp_for_new_connector_integration_accept_dispute!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -915,10 +903,8 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -940,7 +926,6 @@ default_imp_for_new_connector_integration_defend_dispute!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -949,10 +934,8 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -974,7 +957,6 @@ default_imp_for_new_connector_integration_submit_evidence!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1010,10 +992,8 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1035,7 +1015,6 @@ default_imp_for_new_connector_integration_file_upload!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1120,7 +1099,6 @@ default_imp_for_new_connector_integration_payouts!(
connector::Tsys,
connector::UnifiedAuthenticationService,
connector::Volt,
- connector::Wellsfargo,
connector::Wise,
connector::Worldline,
connector::Worldpay,
@@ -1152,10 +1130,8 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1177,7 +1153,6 @@ default_imp_for_new_connector_integration_payouts_create!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1205,10 +1180,8 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1230,7 +1203,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1258,10 +1230,8 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1283,7 +1253,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1311,10 +1280,8 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1336,7 +1303,6 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1364,10 +1330,8 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1389,7 +1353,6 @@ default_imp_for_new_connector_integration_payouts_quote!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1417,10 +1380,8 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1442,7 +1403,6 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1470,10 +1430,8 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1495,7 +1453,6 @@ default_imp_for_new_connector_integration_payouts_sync!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1523,10 +1480,8 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1548,7 +1503,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1574,10 +1528,8 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1599,7 +1551,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1621,7 +1572,6 @@ default_imp_for_new_connector_integration_frm!(
connector::Authorizedotnet,
connector::Bambora,
connector::Bamboraapac,
- connector::Bankofamerica,
connector::Billwerk,
connector::Bitpay,
connector::Bluesnap,
@@ -1631,7 +1581,6 @@ default_imp_for_new_connector_integration_frm!(
connector::Checkout,
connector::Cryptopay,
connector::Coinbase,
- connector::Cybersource,
connector::Deutschebank,
connector::Digitalvirgo,
connector::Dlocal,
@@ -1686,7 +1635,6 @@ default_imp_for_new_connector_integration_frm!(
connector::Tsys,
connector::UnifiedAuthenticationService,
connector::Volt,
- connector::Wellsfargo,
connector::Wise,
connector::Worldline,
connector::Worldpay,
@@ -1718,10 +1666,8 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1743,7 +1689,6 @@ default_imp_for_new_connector_integration_frm_sale!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1771,10 +1716,8 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1796,7 +1739,6 @@ default_imp_for_new_connector_integration_frm_checkout!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1824,10 +1766,8 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1849,7 +1789,6 @@ default_imp_for_new_connector_integration_frm_transaction!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1877,10 +1816,8 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1902,7 +1839,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1930,10 +1866,8 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1955,7 +1889,6 @@ default_imp_for_new_connector_integration_frm_record_return!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -1980,10 +1913,8 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2005,7 +1936,6 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connector::Stripe,
connector::Trustpay,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wise,
connector::Plaid
);
@@ -2129,7 +2059,6 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Tsys,
connector::UnifiedAuthenticationService,
connector::Volt,
- connector::Wellsfargo,
connector::Wise,
connector::Worldline,
connector::Worldpay,
@@ -2169,10 +2098,8 @@ default_imp_for_new_connector_integration_uas!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2195,7 +2122,6 @@ default_imp_for_new_connector_integration_uas!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 925fb0f12bc..9ce3ad6c020 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -215,7 +215,6 @@ default_imp_for_complete_authorize!(
connector::Adyenplatform,
connector::Aci,
connector::Adyen,
- connector::Bankofamerica,
connector::Checkout,
connector::Ebanx,
connector::Gpayments,
@@ -235,7 +234,6 @@ default_imp_for_complete_authorize!(
connector::Threedsecureio,
connector::Trustpay,
connector::Wise,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
macro_rules! default_imp_for_webhook_source_verification {
@@ -269,10 +267,8 @@ default_imp_for_webhook_source_verification!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -294,7 +290,6 @@ default_imp_for_webhook_source_verification!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -331,10 +326,8 @@ default_imp_for_create_customer!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -356,7 +349,6 @@ default_imp_for_create_customer!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -394,8 +386,6 @@ default_imp_for_connector_redirect_response!(
connector::Adyenplatform,
connector::Aci,
connector::Adyen,
- connector::Bankofamerica,
- connector::Cybersource,
connector::Ebanx,
connector::Gpayments,
connector::Iatapay,
@@ -410,7 +400,6 @@ default_imp_for_connector_redirect_response!(
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -547,9 +536,7 @@ default_imp_for_accept_dispute!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -572,7 +559,6 @@ default_imp_for_accept_dispute!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -630,9 +616,7 @@ default_imp_for_file_upload!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -654,7 +638,6 @@ default_imp_for_file_upload!(
connector::Threedsecureio,
connector::Trustpay,
connector::Opennode,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -690,9 +673,7 @@ default_imp_for_submit_evidence!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -714,7 +695,6 @@ default_imp_for_submit_evidence!(
connector::Threedsecureio,
connector::Trustpay,
connector::Opennode,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -750,9 +730,7 @@ default_imp_for_defend_dispute!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -775,7 +753,6 @@ default_imp_for_defend_dispute!(
connector::Threedsecureio,
connector::Trustpay,
connector::Opennode,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -826,7 +803,6 @@ default_imp_for_pre_processing_steps!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
connector::Ebanx,
@@ -845,7 +821,6 @@ default_imp_for_pre_processing_steps!(
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -865,8 +840,6 @@ impl<const T: u8>
default_imp_for_post_processing_steps!(
connector::Adyenplatform,
connector::Adyen,
- connector::Bankofamerica,
- connector::Cybersource,
connector::Nmi,
connector::Nuvei,
connector::Payme,
@@ -892,7 +865,6 @@ default_imp_for_post_processing_steps!(
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -911,7 +883,6 @@ impl<const T: u8> Payouts for connector::DummyConnector<T> {}
default_imp_for_payouts!(
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
connector::Globalpay,
@@ -932,7 +903,6 @@ default_imp_for_payouts!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -968,10 +938,8 @@ default_imp_for_payouts_create!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -991,7 +959,6 @@ default_imp_for_payouts_create!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1028,10 +995,8 @@ default_imp_for_payouts_retrieve!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1053,7 +1018,6 @@ default_imp_for_payouts_retrieve!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1093,10 +1057,8 @@ default_imp_for_payouts_eligibility!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -1118,7 +1080,6 @@ default_imp_for_payouts_eligibility!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1153,7 +1114,6 @@ impl<const T: u8>
default_imp_for_payouts_fulfill!(
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
connector::Globalpay,
@@ -1174,7 +1134,6 @@ default_imp_for_payouts_fulfill!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1210,10 +1169,8 @@ default_imp_for_payouts_cancel!(
connector::Adyenplatform,
connector::Aci,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -1234,7 +1191,6 @@ default_imp_for_payouts_cancel!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1271,10 +1227,8 @@ default_imp_for_payouts_quote!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -1296,7 +1250,6 @@ default_imp_for_payouts_quote!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1333,10 +1286,8 @@ default_imp_for_payouts_recipient!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Globalpay,
connector::Gpayments,
connector::Iatapay,
@@ -1357,7 +1308,6 @@ default_imp_for_payouts_recipient!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout
);
@@ -1397,10 +1347,8 @@ default_imp_for_payouts_recipient_account!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1422,7 +1370,6 @@ default_imp_for_payouts_recipient_account!(
connector::Signifyd,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1459,10 +1406,8 @@ default_imp_for_approve!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1485,7 +1430,6 @@ default_imp_for_approve!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1522,10 +1466,8 @@ default_imp_for_reject!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1548,7 +1490,6 @@ default_imp_for_reject!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1685,10 +1626,8 @@ default_imp_for_frm_sale!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1709,7 +1648,6 @@ default_imp_for_frm_sale!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1748,10 +1686,8 @@ default_imp_for_frm_checkout!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1772,7 +1708,6 @@ default_imp_for_frm_checkout!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1811,10 +1746,8 @@ default_imp_for_frm_transaction!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1835,7 +1768,6 @@ default_imp_for_frm_transaction!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1874,10 +1806,8 @@ default_imp_for_frm_fulfillment!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1898,7 +1828,6 @@ default_imp_for_frm_fulfillment!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1937,10 +1866,8 @@ default_imp_for_frm_record_return!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -1961,7 +1888,6 @@ default_imp_for_frm_record_return!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1998,7 +1924,6 @@ default_imp_for_incremental_authorization!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
connector::Ebanx,
@@ -2057,7 +1982,6 @@ default_imp_for_revoking_mandates!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
connector::Ebanx,
@@ -2285,10 +2209,8 @@ default_imp_for_authorize_session_token!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2310,7 +2232,6 @@ default_imp_for_authorize_session_token!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2345,10 +2266,8 @@ default_imp_for_calculate_tax!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2371,7 +2290,6 @@ default_imp_for_calculate_tax!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2406,10 +2324,8 @@ default_imp_for_session_update!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2431,7 +2347,6 @@ default_imp_for_session_update!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2466,10 +2381,8 @@ default_imp_for_post_session_tokens!(
connector::Adyen,
connector::Adyenplatform,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2491,7 +2404,6 @@ default_imp_for_post_session_tokens!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2529,10 +2441,8 @@ default_imp_for_uas_pre_authentication!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2555,7 +2465,6 @@ default_imp_for_uas_pre_authentication!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2590,10 +2499,8 @@ default_imp_for_uas_post_authentication!(
connector::Aci,
connector::Adyen,
connector::Authorizedotnet,
- connector::Bankofamerica,
connector::Braintree,
connector::Checkout,
- connector::Cybersource,
connector::Ebanx,
connector::Globalpay,
connector::Gpayments,
@@ -2616,7 +2523,6 @@ default_imp_for_uas_post_authentication!(
connector::Stripe,
connector::Threedsecureio,
connector::Trustpay,
- connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise
);
|
2024-12-20T10:56:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Move cybersource, bankofamerica, wellsfargo code to crate hyperswitch_connectors.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
https://github.com/juspay/hyperswitch/issues/6585
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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?
Moved the connector tot he hyperswitch crate (No logical Changes)
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
9c1ebd219fcaeefb6bd06c21c2358bf19a332891
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6553
|
Bug: feat(themes): APIs for theme management
Backend needs to provide APIs to create and manage themes. Four APIs are planned
1. Create theme
2. Update theme data
3. Delete theme
4. Upload an asset to theme

|
diff --git a/Cargo.lock b/Cargo.lock
index 4118ea29c2d..9b0263f99dc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -455,6 +455,7 @@ checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"
name = "api_models"
version = "0.1.0"
dependencies = [
+ "actix-multipart",
"actix-web",
"cards",
"common_enums",
diff --git a/config/config.example.toml b/config/config.example.toml
index 03ebedf0d35..54a3ab3827b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -795,3 +795,6 @@ connector_list = "stripe,adyen,cybersource" # Supported connectors for network t
host = "localhost" # Client Host
port = 7000 # Client Port
service = "dynamo" # Service name
+
+[theme_storage]
+file_storage_backend = "file_system" # Theme storage backend to be used
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index fa0c0484a77..5cadc66ddfc 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -327,3 +327,10 @@ check_token_status_url= "" # base url to check token status from token servic
host = "localhost" # Client Host
port = 7000 # Client Port
service = "dynamo" # Service name
+
+[theme_storage]
+file_storage_backend = "aws_s3" # Theme storage backend to be used
+
+[theme_storage.aws_s3]
+region = "bucket_region" # AWS region where the S3 bucket for theme storage is located
+bucket_name = "bucket" # AWS S3 bucket name for theme storage
diff --git a/config/development.toml b/config/development.toml
index d8251cfce7b..eef44648c6c 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -793,3 +793,6 @@ connector_list = "cybersource"
[grpc_client.dynamic_routing_client]
host = "localhost"
port = 7000
+
+[theme_storage]
+file_storage_backend = "file_system"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 976a2fa2a42..f38da4183b1 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -691,3 +691,6 @@ prod_intent_recipient_email = "business@example.com" # Recipient email for prod
[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.
+
+[theme_storage]
+file_storage_backend = "file_system" # Theme storage backend to be used
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index a5d702e26fb..eb706dc913c 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -8,7 +8,7 @@ readme = "README.md"
license.workspace = true
[features]
-errors = ["dep:actix-web", "dep:reqwest"]
+errors = ["dep:reqwest"]
dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"]
detailed_errors = []
payouts = ["common_enums/payouts"]
@@ -23,7 +23,8 @@ payment_methods_v2 = ["common_utils/payment_methods_v2"]
dynamic_routing = []
[dependencies]
-actix-web = { version = "4.5.1", optional = true }
+actix-multipart = "0.6.1"
+actix-web = "4.5.1"
error-stack = "0.4.1"
indexmap = "2.3.0"
mime = "0.3.17"
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 4dc2a1a301a..3260ef02645 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -10,6 +10,7 @@ use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
+ theme::{CreateThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest},
AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse,
ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,
CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest,
@@ -74,7 +75,11 @@ common_utils::impl_api_event_type!(
UpdateUserAuthenticationMethodRequest,
GetSsoAuthUrlRequest,
SsoSignInRequest,
- AuthSelectRequest
+ AuthSelectRequest,
+ GetThemeResponse,
+ UploadFileRequest,
+ CreateThemeRequest,
+ UpdateThemeRequest
)
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 089426c68ba..5dc3f544297 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -8,6 +8,7 @@ use crate::user_role::UserStatus;
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
+pub mod theme;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
pub struct SignUpWithMerchantIdRequest {
diff --git a/crates/api_models/src/user/theme.rs b/crates/api_models/src/user/theme.rs
new file mode 100644
index 00000000000..23218c4a163
--- /dev/null
+++ b/crates/api_models/src/user/theme.rs
@@ -0,0 +1,125 @@
+use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
+use common_enums::EntityType;
+use common_utils::{id_type, types::theme::ThemeLineage};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Serialize)]
+pub struct GetThemeResponse {
+ pub theme_id: String,
+ pub theme_name: String,
+ pub entity_type: EntityType,
+ pub tenant_id: id_type::TenantId,
+ pub org_id: Option<id_type::OrganizationId>,
+ pub merchant_id: Option<id_type::MerchantId>,
+ pub profile_id: Option<id_type::ProfileId>,
+ pub theme_data: ThemeData,
+}
+
+#[derive(Debug, MultipartForm)]
+pub struct UploadFileAssetData {
+ pub asset_name: Text<String>,
+ #[multipart(limit = "10MB")]
+ pub asset_data: Bytes,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct UploadFileRequest {
+ pub lineage: ThemeLineage,
+ pub asset_name: String,
+ pub asset_data: Secret<Vec<u8>>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct CreateThemeRequest {
+ pub lineage: ThemeLineage,
+ pub theme_name: String,
+ pub theme_data: ThemeData,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct UpdateThemeRequest {
+ pub lineage: ThemeLineage,
+ pub theme_data: ThemeData,
+}
+
+// All the below structs are for the theme.json file,
+// which will be used by frontend to style the dashboard.
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ThemeData {
+ settings: Settings,
+ urls: Option<Urls>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Settings {
+ colors: Colors,
+ typography: Option<Typography>,
+ buttons: Buttons,
+ borders: Option<Borders>,
+ spacing: Option<Spacing>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Colors {
+ primary: String,
+ sidebar: String,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Typography {
+ font_family: Option<String>,
+ font_size: Option<String>,
+ heading_font_size: Option<String>,
+ text_color: Option<String>,
+ link_color: Option<String>,
+ link_hover_color: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Buttons {
+ primary: PrimaryButton,
+ secondary: Option<SecondaryButton>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct PrimaryButton {
+ background_color: Option<String>,
+ text_color: Option<String>,
+ hover_background_color: String,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct SecondaryButton {
+ background_color: Option<String>,
+ text_color: Option<String>,
+ hover_background_color: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Borders {
+ default_radius: Option<String>,
+ border_color: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Spacing {
+ padding: Option<String>,
+ margin: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct Urls {
+ favicon_url: Option<String>,
+ logo_url: Option<String>,
+}
diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs
index 9ad9206acce..239cffc40d4 100644
--- a/crates/common_utils/src/types/theme.rs
+++ b/crates/common_utils/src/types/theme.rs
@@ -1,8 +1,14 @@
-use crate::id_type;
+use common_enums::EntityType;
+
+use crate::{
+ events::{ApiEventMetric, ApiEventsType},
+ id_type, impl_api_event_type,
+};
/// Enum for having all the required lineage for every level.
/// Currently being used for theme related APIs and queries.
-#[derive(Debug)]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[serde(tag = "entity_type", rename_all = "snake_case")]
pub enum ThemeLineage {
// TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType
// /// Tenant lineage variant
@@ -38,3 +44,52 @@ pub enum ThemeLineage {
profile_id: id_type::ProfileId,
},
}
+
+impl_api_event_type!(Miscellaneous, (ThemeLineage));
+
+impl ThemeLineage {
+ /// Get the entity_type from the lineage
+ pub fn entity_type(&self) -> EntityType {
+ match self {
+ Self::Organization { .. } => EntityType::Organization,
+ Self::Merchant { .. } => EntityType::Merchant,
+ Self::Profile { .. } => EntityType::Profile,
+ }
+ }
+
+ /// Get the tenant_id from the lineage
+ pub fn tenant_id(&self) -> &id_type::TenantId {
+ match self {
+ Self::Organization { tenant_id, .. }
+ | Self::Merchant { tenant_id, .. }
+ | Self::Profile { tenant_id, .. } => tenant_id,
+ }
+ }
+
+ /// Get the org_id from the lineage
+ pub fn org_id(&self) -> Option<&id_type::OrganizationId> {
+ match self {
+ Self::Organization { org_id, .. }
+ | Self::Merchant { org_id, .. }
+ | Self::Profile { org_id, .. } => Some(org_id),
+ }
+ }
+
+ /// Get the merchant_id from the lineage
+ pub fn merchant_id(&self) -> Option<&id_type::MerchantId> {
+ match self {
+ Self::Organization { .. } => None,
+ Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => {
+ Some(merchant_id)
+ }
+ }
+ }
+
+ /// Get the profile_id from the lineage
+ pub fn profile_id(&self) -> Option<&id_type::ProfileId> {
+ match self {
+ Self::Organization { .. } | Self::Merchant { .. } => None,
+ Self::Profile { profile_id, .. } => Some(profile_id),
+ }
+ }
+}
diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs
index 78fd5025ef9..a26e401ffbb 100644
--- a/crates/diesel_models/src/query/user/theme.rs
+++ b/crates/diesel_models/src/query/user/theme.rs
@@ -69,6 +69,14 @@ impl Theme {
}
}
+ pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::theme_id.eq(theme_id),
+ )
+ .await
+ }
+
pub async fn find_by_lineage(
conn: &PgPooledConn,
lineage: ThemeLineage,
diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs
index 9841e21443c..e43a182126b 100644
--- a/crates/diesel_models/src/user/theme.rs
+++ b/crates/diesel_models/src/user/theme.rs
@@ -1,5 +1,5 @@
use common_enums::EntityType;
-use common_utils::id_type;
+use common_utils::{date_time, id_type, types::theme::ThemeLineage};
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
@@ -32,3 +32,21 @@ pub struct ThemeNew {
pub entity_type: EntityType,
pub theme_name: String,
}
+
+impl ThemeNew {
+ pub fn new(theme_id: String, theme_name: String, lineage: ThemeLineage) -> Self {
+ let now = date_time::now();
+
+ Self {
+ theme_id,
+ theme_name,
+ tenant_id: lineage.tenant_id().to_owned(),
+ org_id: lineage.org_id().cloned(),
+ merchant_id: lineage.merchant_id().cloned(),
+ profile_id: lineage.profile_id().cloned(),
+ entity_type: lineage.entity_type(),
+ created_at: now,
+ last_modified_at: now,
+ }
+ }
+}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index dbdba189ed1..3ab56266b55 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -545,5 +545,6 @@ pub(crate) async fn fetch_raw_secrets(
.network_tokenization_supported_card_networks,
network_tokenization_service,
network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors,
+ theme_storage: conf.theme_storage,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 4e559a261b9..1da4a33f5f3 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -128,6 +128,7 @@ pub struct Settings<S: SecretState> {
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
+ pub theme_storage: FileStorageConfig,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -886,6 +887,10 @@ impl Settings<SecuredSecret> {
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
+ self.theme_storage
+ .validate()
+ .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
+
Ok(())
}
}
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 5c7b77246e2..33477df6330 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -96,6 +96,16 @@ pub enum UserErrors {
MaxRecoveryCodeAttemptsReached,
#[error("Forbidden tenant id")]
ForbiddenTenantId,
+ #[error("Error Uploading file to Theme Storage")]
+ ErrorUploadingFile,
+ #[error("Error Retrieving file from Theme Storage")]
+ ErrorRetrievingFile,
+ #[error("Theme not found")]
+ ThemeNotFound,
+ #[error("Theme with lineage already exists")]
+ ThemeAlreadyExists,
+ #[error("Invalid field: {0} in lineage")]
+ InvalidThemeLineage(String),
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -244,57 +254,93 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::ForbiddenTenantId => {
AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None))
}
+ Self::ErrorUploadingFile => AER::InternalServerError(ApiError::new(
+ sub_code,
+ 51,
+ self.get_error_message(),
+ None,
+ )),
+ Self::ErrorRetrievingFile => AER::InternalServerError(ApiError::new(
+ sub_code,
+ 52,
+ self.get_error_message(),
+ None,
+ )),
+ Self::ThemeNotFound => {
+ AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
+ }
+ Self::ThemeAlreadyExists => {
+ AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
+ }
+ Self::InvalidThemeLineage(_) => {
+ AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None))
+ }
}
}
}
impl UserErrors {
- pub fn get_error_message(&self) -> &str {
+ pub fn get_error_message(&self) -> String {
match self {
- Self::InternalServerError => "Something went wrong",
- Self::InvalidCredentials => "Incorrect email or password",
- Self::UserNotFound => "Email doesn’t exist. Register",
- Self::UserExists => "An account already exists with this email",
- Self::LinkInvalid => "Invalid or expired link",
- Self::UnverifiedUser => "Kindly verify your account",
- Self::InvalidOldPassword => "Old password incorrect. Please enter the correct password",
- Self::EmailParsingError => "Invalid Email",
- Self::NameParsingError => "Invalid Name",
- Self::PasswordParsingError => "Invalid Password",
- Self::UserAlreadyVerified => "User already verified",
- Self::CompanyNameParsingError => "Invalid Company Name",
- Self::MerchantAccountCreationError(error_message) => error_message,
- Self::InvalidEmailError => "Invalid Email",
- Self::MerchantIdNotFound => "Invalid Merchant ID",
- Self::MetadataAlreadySet => "Metadata already set",
- Self::DuplicateOrganizationId => "An Organization with the id already exists",
- Self::InvalidRoleId => "Invalid Role ID",
- Self::InvalidRoleOperation => "User Role Operation Not Supported",
- Self::IpAddressParsingFailed => "Something went wrong",
- Self::InvalidMetadataRequest => "Invalid Metadata Request",
- Self::MerchantIdParsingError => "Invalid Merchant Id",
- Self::ChangePasswordError => "Old and new password cannot be same",
- Self::InvalidDeleteOperation => "Delete Operation Not Supported",
- Self::MaxInvitationsError => "Maximum invite count per request exceeded",
- Self::RoleNotFound => "Role Not Found",
- Self::InvalidRoleOperationWithMessage(error_message) => error_message,
- Self::RoleNameParsingError => "Invalid Role Name",
- Self::RoleNameAlreadyExists => "Role name already exists",
- Self::TotpNotSetup => "TOTP not setup",
- 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",
- Self::UserAuthMethodAlreadyExists => "User auth method already exists",
- Self::InvalidUserAuthMethodOperation => "Invalid user auth method operation",
- Self::AuthConfigParsingError => "Auth config parsing error",
- Self::SSOFailed => "Invalid SSO request",
- Self::JwtProfileIdMissing => "profile_id missing in JWT",
- Self::ForbiddenTenantId => "Forbidden tenant id",
+ Self::InternalServerError => "Something went wrong".to_string(),
+ Self::InvalidCredentials => "Incorrect email or password".to_string(),
+ Self::UserNotFound => "Email doesn’t exist. Register".to_string(),
+ Self::UserExists => "An account already exists with this email".to_string(),
+ Self::LinkInvalid => "Invalid or expired link".to_string(),
+ Self::UnverifiedUser => "Kindly verify your account".to_string(),
+ Self::InvalidOldPassword => {
+ "Old password incorrect. Please enter the correct password".to_string()
+ }
+ Self::EmailParsingError => "Invalid Email".to_string(),
+ Self::NameParsingError => "Invalid Name".to_string(),
+ Self::PasswordParsingError => "Invalid Password".to_string(),
+ Self::UserAlreadyVerified => "User already verified".to_string(),
+ Self::CompanyNameParsingError => "Invalid Company Name".to_string(),
+ Self::MerchantAccountCreationError(error_message) => error_message.to_string(),
+ Self::InvalidEmailError => "Invalid Email".to_string(),
+ Self::MerchantIdNotFound => "Invalid Merchant ID".to_string(),
+ Self::MetadataAlreadySet => "Metadata already set".to_string(),
+ Self::DuplicateOrganizationId => {
+ "An Organization with the id already exists".to_string()
+ }
+ Self::InvalidRoleId => "Invalid Role ID".to_string(),
+ Self::InvalidRoleOperation => "User Role Operation Not Supported".to_string(),
+ Self::IpAddressParsingFailed => "Something went wrong".to_string(),
+ Self::InvalidMetadataRequest => "Invalid Metadata Request".to_string(),
+ Self::MerchantIdParsingError => "Invalid Merchant Id".to_string(),
+ Self::ChangePasswordError => "Old and new password cannot be same".to_string(),
+ Self::InvalidDeleteOperation => "Delete Operation Not Supported".to_string(),
+ Self::MaxInvitationsError => "Maximum invite count per request exceeded".to_string(),
+ Self::RoleNotFound => "Role Not Found".to_string(),
+ Self::InvalidRoleOperationWithMessage(error_message) => error_message.to_string(),
+ Self::RoleNameParsingError => "Invalid Role Name".to_string(),
+ Self::RoleNameAlreadyExists => "Role name already exists".to_string(),
+ Self::TotpNotSetup => "TOTP not setup".to_string(),
+ Self::InvalidTotp => "Invalid TOTP".to_string(),
+ Self::TotpRequired => "TOTP required".to_string(),
+ Self::InvalidRecoveryCode => "Invalid Recovery Code".to_string(),
+ Self::MaxTotpAttemptsReached => "Maximum attempts reached for TOTP".to_string(),
+ Self::MaxRecoveryCodeAttemptsReached => {
+ "Maximum attempts reached for Recovery Code".to_string()
+ }
+ Self::TwoFactorAuthRequired => "Two factor auth required".to_string(),
+ Self::TwoFactorAuthNotSetup => "Two factor auth not setup".to_string(),
+ Self::TotpSecretNotFound => "TOTP secret not found".to_string(),
+ Self::UserAuthMethodAlreadyExists => "User auth method already exists".to_string(),
+ Self::InvalidUserAuthMethodOperation => {
+ "Invalid user auth method operation".to_string()
+ }
+ Self::AuthConfigParsingError => "Auth config parsing error".to_string(),
+ Self::SSOFailed => "Invalid SSO request".to_string(),
+ Self::JwtProfileIdMissing => "profile_id missing in JWT".to_string(),
+ Self::ForbiddenTenantId => "Forbidden tenant id".to_string(),
+ Self::ErrorUploadingFile => "Error Uploading file to Theme Storage".to_string(),
+ Self::ErrorRetrievingFile => "Error Retrieving file from Theme Storage".to_string(),
+ Self::ThemeNotFound => "Theme not found".to_string(),
+ Self::ThemeAlreadyExists => "Theme with lineage already exists".to_string(),
+ Self::InvalidThemeLineage(field_name) => {
+ format!("Invalid field: {} in lineage", field_name)
+ }
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 039e891e422..027f89b5cc1 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -44,6 +44,7 @@ use crate::{
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
+pub mod theme;
#[cfg(feature = "email")]
pub async fn signup_with_merchant_id(
diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs
new file mode 100644
index 00000000000..dbf11256a50
--- /dev/null
+++ b/crates/router/src/core/user/theme.rs
@@ -0,0 +1,225 @@
+use api_models::user::theme as theme_api;
+use common_utils::{
+ ext_traits::{ByteSliceExt, Encode},
+ types::theme::ThemeLineage,
+};
+use diesel_models::user::theme::ThemeNew;
+use error_stack::ResultExt;
+use hyperswitch_domain_models::api::ApplicationResponse;
+use masking::ExposeInterface;
+use rdkafka::message::ToBytes;
+use uuid::Uuid;
+
+use crate::{
+ core::errors::{StorageErrorExt, UserErrors, UserResponse},
+ routes::SessionState,
+ utils::user::theme as theme_utils,
+};
+
+pub async fn get_theme_using_lineage(
+ state: SessionState,
+ lineage: ThemeLineage,
+) -> UserResponse<theme_api::GetThemeResponse> {
+ let theme = state
+ .global_store
+ .find_theme_by_lineage(lineage)
+ .await
+ .to_not_found_response(UserErrors::ThemeNotFound)?;
+
+ let file = theme_utils::retrieve_file_from_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&theme.theme_id),
+ )
+ .await?;
+
+ let parsed_data = file
+ .to_bytes()
+ .parse_struct("ThemeData")
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ theme_id: theme.theme_id,
+ theme_name: theme.theme_name,
+ entity_type: theme.entity_type,
+ tenant_id: theme.tenant_id,
+ org_id: theme.org_id,
+ merchant_id: theme.merchant_id,
+ profile_id: theme.profile_id,
+ theme_data: parsed_data,
+ }))
+}
+
+pub async fn get_theme_using_theme_id(
+ state: SessionState,
+ theme_id: String,
+) -> UserResponse<theme_api::GetThemeResponse> {
+ let theme = state
+ .global_store
+ .find_theme_by_theme_id(theme_id.clone())
+ .await
+ .to_not_found_response(UserErrors::ThemeNotFound)?;
+
+ let file = theme_utils::retrieve_file_from_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&theme_id),
+ )
+ .await?;
+
+ let parsed_data = file
+ .to_bytes()
+ .parse_struct("ThemeData")
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ theme_id: theme.theme_id,
+ theme_name: theme.theme_name,
+ entity_type: theme.entity_type,
+ tenant_id: theme.tenant_id,
+ org_id: theme.org_id,
+ merchant_id: theme.merchant_id,
+ profile_id: theme.profile_id,
+ theme_data: parsed_data,
+ }))
+}
+
+pub async fn upload_file_to_theme_storage(
+ state: SessionState,
+ theme_id: String,
+ request: theme_api::UploadFileRequest,
+) -> UserResponse<()> {
+ let db_theme = state
+ .global_store
+ .find_theme_by_lineage(request.lineage)
+ .await
+ .to_not_found_response(UserErrors::ThemeNotFound)?;
+
+ if theme_id != db_theme.theme_id {
+ return Err(UserErrors::ThemeNotFound.into());
+ }
+
+ theme_utils::upload_file_to_theme_bucket(
+ &state,
+ &theme_utils::get_specific_file_key(&theme_id, &request.asset_name),
+ request.asset_data.expose(),
+ )
+ .await?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+pub async fn create_theme(
+ state: SessionState,
+ request: theme_api::CreateThemeRequest,
+) -> UserResponse<theme_api::GetThemeResponse> {
+ theme_utils::validate_lineage(&state, &request.lineage).await?;
+
+ let new_theme = ThemeNew::new(
+ Uuid::new_v4().to_string(),
+ request.theme_name,
+ request.lineage,
+ );
+
+ let db_theme = state
+ .global_store
+ .insert_theme(new_theme)
+ .await
+ .to_duplicate_response(UserErrors::ThemeAlreadyExists)?;
+
+ theme_utils::upload_file_to_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&db_theme.theme_id),
+ request
+ .theme_data
+ .encode_to_vec()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await?;
+
+ let file = theme_utils::retrieve_file_from_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&db_theme.theme_id),
+ )
+ .await?;
+
+ let parsed_data = file
+ .to_bytes()
+ .parse_struct("ThemeData")
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ theme_id: db_theme.theme_id,
+ entity_type: db_theme.entity_type,
+ tenant_id: db_theme.tenant_id,
+ org_id: db_theme.org_id,
+ merchant_id: db_theme.merchant_id,
+ profile_id: db_theme.profile_id,
+ theme_name: db_theme.theme_name,
+ theme_data: parsed_data,
+ }))
+}
+
+pub async fn update_theme(
+ state: SessionState,
+ theme_id: String,
+ request: theme_api::UpdateThemeRequest,
+) -> UserResponse<theme_api::GetThemeResponse> {
+ let db_theme = state
+ .global_store
+ .find_theme_by_lineage(request.lineage)
+ .await
+ .to_not_found_response(UserErrors::ThemeNotFound)?;
+
+ if theme_id != db_theme.theme_id {
+ return Err(UserErrors::ThemeNotFound.into());
+ }
+
+ theme_utils::upload_file_to_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&db_theme.theme_id),
+ request
+ .theme_data
+ .encode_to_vec()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await?;
+
+ let file = theme_utils::retrieve_file_from_theme_bucket(
+ &state,
+ &theme_utils::get_theme_file_key(&db_theme.theme_id),
+ )
+ .await?;
+
+ let parsed_data = file
+ .to_bytes()
+ .parse_struct("ThemeData")
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ theme_id: db_theme.theme_id,
+ entity_type: db_theme.entity_type,
+ tenant_id: db_theme.tenant_id,
+ org_id: db_theme.org_id,
+ merchant_id: db_theme.merchant_id,
+ profile_id: db_theme.profile_id,
+ theme_name: db_theme.theme_name,
+ theme_data: parsed_data,
+ }))
+}
+
+pub async fn delete_theme(
+ state: SessionState,
+ theme_id: String,
+ lineage: ThemeLineage,
+) -> UserResponse<()> {
+ state
+ .global_store
+ .delete_theme_by_lineage_and_theme_id(theme_id.clone(), lineage)
+ .await
+ .to_not_found_response(UserErrors::ThemeNotFound)?;
+
+ // TODO (#6717): Delete theme folder from the theme storage.
+ // Currently there is no simple or easy way to delete a whole folder from S3.
+ // So, we are not deleting the theme folder from the theme storage.
+
+ Ok(ApplicationResponse::StatusOk)
+}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index ec45d9e18d7..9a284f1399d 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3723,6 +3723,13 @@ impl ThemeInterface for KafkaStore {
self.diesel_store.insert_theme(theme).await
}
+ async fn find_theme_by_theme_id(
+ &self,
+ theme_id: String,
+ ) -> CustomResult<storage::theme::Theme, errors::StorageError> {
+ self.diesel_store.find_theme_by_theme_id(theme_id).await
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs
index f1e4f4f794e..9b55a98d0ad 100644
--- a/crates/router/src/db/user/theme.rs
+++ b/crates/router/src/db/user/theme.rs
@@ -16,6 +16,11 @@ pub trait ThemeInterface {
theme: storage::ThemeNew,
) -> CustomResult<storage::Theme, errors::StorageError>;
+ async fn find_theme_by_theme_id(
+ &self,
+ theme_id: String,
+ ) -> CustomResult<storage::Theme, errors::StorageError>;
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
@@ -41,6 +46,16 @@ impl ThemeInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ async fn find_theme_by_theme_id(
+ &self,
+ theme_id: String,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Theme::find_by_theme_id(&conn, theme_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
@@ -165,6 +180,24 @@ impl ThemeInterface for MockDb {
Ok(theme)
}
+ async fn find_theme_by_theme_id(
+ &self,
+ theme_id: String,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let themes = self.themes.lock().await;
+ themes
+ .iter()
+ .find(|theme| theme.theme_id == theme_id)
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "Theme with id {} not found",
+ theme_id
+ ))
+ .into(),
+ )
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bb8d0d4f2bd..9f4b413ac5b 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -110,6 +110,7 @@ pub struct SessionState {
#[cfg(feature = "olap")]
pub opensearch_client: Arc<OpenSearchClient>,
pub grpc_client: Arc<GrpcClients>,
+ pub theme_storage_client: Arc<dyn FileStorageInterface>,
}
impl scheduler::SchedulerSessionState for SessionState {
fn get_db(&self) -> Box<dyn SchedulerInterface> {
@@ -208,6 +209,7 @@ pub struct AppState {
pub file_storage_client: Arc<dyn FileStorageInterface>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
pub grpc_client: Arc<GrpcClients>,
+ pub theme_storage_client: Arc<dyn FileStorageInterface>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<id_type::TenantId> {
@@ -367,6 +369,7 @@ impl AppState {
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
+ let theme_storage_client = conf.theme_storage.get_file_storage_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
@@ -387,6 +390,7 @@ impl AppState {
file_storage_client,
encryption_client,
grpc_client,
+ theme_storage_client,
}
})
.await
@@ -472,6 +476,7 @@ impl AppState {
#[cfg(feature = "olap")]
opensearch_client: Arc::clone(&self.opensearch_client),
grpc_client: Arc::clone(&self.grpc_client),
+ theme_storage_client: self.theme_storage_client.clone(),
})
}
}
@@ -2127,6 +2132,23 @@ impl User {
.route(web::delete().to(user::delete_sample_data)),
)
}
+
+ route = route.service(
+ web::scope("/theme")
+ .service(
+ web::resource("")
+ .route(web::get().to(user::theme::get_theme_using_lineage))
+ .route(web::post().to(user::theme::create_theme)),
+ )
+ .service(
+ web::resource("/{theme_id}")
+ .route(web::get().to(user::theme::get_theme_using_theme_id))
+ .route(web::put().to(user::theme::update_theme))
+ .route(web::post().to(user::theme::upload_file_to_theme_storage))
+ .route(web::delete().to(user::theme::delete_theme)),
+ ),
+ );
+
route
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 4d3718b967d..1c7db127ffc 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -259,7 +259,13 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListMerchantsForUserInOrg
| Flow::ListProfileForUserInOrgAndMerchant
| Flow::ListInvitationsForUser
- | Flow::AuthSelect => Self::User,
+ | Flow::AuthSelect
+ | Flow::GetThemeUsingLineage
+ | Flow::GetThemeUsingThemeId
+ | Flow::UploadFileToThemeStorage
+ | Flow::CreateTheme
+ | Flow::UpdateTheme
+ | Flow::DeleteTheme => Self::User,
Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 8fc0dad452a..9f2060e43cb 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -1,3 +1,5 @@
+pub mod theme;
+
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "dummy_connector")]
use api_models::user::sample_data::SampleDataRequest;
diff --git a/crates/router/src/routes/user/theme.rs b/crates/router/src/routes/user/theme.rs
new file mode 100644
index 00000000000..69a8e9a5378
--- /dev/null
+++ b/crates/router/src/routes/user/theme.rs
@@ -0,0 +1,145 @@
+use actix_multipart::form::MultipartForm;
+use actix_web::{web, HttpRequest, HttpResponse};
+use api_models::user::theme as theme_api;
+use common_utils::types::theme::ThemeLineage;
+use masking::Secret;
+use router_env::Flow;
+
+use crate::{
+ core::{api_locking, user::theme as theme_core},
+ routes::AppState,
+ services::{api, authentication as auth},
+};
+
+pub async fn get_theme_using_lineage(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<ThemeLineage>,
+) -> HttpResponse {
+ let flow = Flow::GetThemeUsingLineage;
+ let lineage = query.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ lineage,
+ |state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn get_theme_using_theme_id(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::GetThemeUsingThemeId;
+ let payload = path.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, payload, _| theme_core::get_theme_using_theme_id(state, payload),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn upload_file_to_theme_storage(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
+ query: web::Query<ThemeLineage>,
+) -> HttpResponse {
+ let flow = Flow::UploadFileToThemeStorage;
+ let theme_id = path.into_inner();
+ let payload = theme_api::UploadFileRequest {
+ lineage: query.into_inner(),
+ asset_name: payload.asset_name.into_inner(),
+ asset_data: Secret::new(payload.asset_data.data.to_vec()),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, payload, _| {
+ theme_core::upload_file_to_theme_storage(state, theme_id.clone(), payload)
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn create_theme(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Json<theme_api::CreateThemeRequest>,
+) -> HttpResponse {
+ let flow = Flow::CreateTheme;
+ let payload = payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, payload, _| theme_core::create_theme(state, payload),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn update_theme(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ payload: web::Json<theme_api::UpdateThemeRequest>,
+) -> HttpResponse {
+ let flow = Flow::UpdateTheme;
+ let theme_id = path.into_inner();
+ let payload = payload.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, payload, _| theme_core::update_theme(state, theme_id.clone(), payload),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn delete_theme(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+ query: web::Query<ThemeLineage>,
+) -> HttpResponse {
+ let flow = Flow::DeleteTheme;
+ let theme_id = path.into_inner();
+ let lineage = query.into_inner();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ lineage,
+ |state, _, lineage, _| theme_core::delete_theme(state, theme_id.clone(), lineage),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 443db741ae3..281b95255c8 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -27,6 +27,7 @@ pub mod dashboard_metadata;
pub mod password;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
+pub mod theme;
pub mod two_factor_auth;
impl UserFromToken {
diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs
new file mode 100644
index 00000000000..13452380d9d
--- /dev/null
+++ b/crates/router/src/utils/user/theme.rs
@@ -0,0 +1,158 @@
+use std::path::PathBuf;
+
+use common_utils::{id_type, types::theme::ThemeLineage};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
+
+use crate::{
+ core::errors::{StorageErrorExt, UserErrors, UserResult},
+ routes::SessionState,
+};
+
+fn get_theme_dir_key(theme_id: &str) -> PathBuf {
+ ["themes", theme_id].iter().collect()
+}
+
+pub fn get_specific_file_key(theme_id: &str, file_name: &str) -> PathBuf {
+ let mut path = get_theme_dir_key(theme_id);
+ path.push(file_name);
+ path
+}
+
+pub fn get_theme_file_key(theme_id: &str) -> PathBuf {
+ get_specific_file_key(theme_id, "theme.json")
+}
+
+fn path_buf_to_str(path: &PathBuf) -> UserResult<&str> {
+ path.to_str()
+ .ok_or(UserErrors::InternalServerError)
+ .attach_printable(format!("Failed to convert path {:#?} to string", path))
+}
+
+pub async fn retrieve_file_from_theme_bucket(
+ state: &SessionState,
+ path: &PathBuf,
+) -> UserResult<Vec<u8>> {
+ state
+ .theme_storage_client
+ .retrieve_file(path_buf_to_str(path)?)
+ .await
+ .change_context(UserErrors::ErrorRetrievingFile)
+}
+
+pub async fn upload_file_to_theme_bucket(
+ state: &SessionState,
+ path: &PathBuf,
+ data: Vec<u8>,
+) -> UserResult<()> {
+ state
+ .theme_storage_client
+ .upload_file(path_buf_to_str(path)?, data)
+ .await
+ .change_context(UserErrors::ErrorUploadingFile)
+}
+
+pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> {
+ match lineage {
+ ThemeLineage::Organization { tenant_id, org_id } => {
+ validate_tenant(state, tenant_id)?;
+ validate_org(state, org_id).await?;
+ Ok(())
+ }
+ ThemeLineage::Merchant {
+ tenant_id,
+ org_id,
+ merchant_id,
+ } => {
+ validate_tenant(state, tenant_id)?;
+ validate_org(state, org_id).await?;
+ validate_merchant(state, org_id, merchant_id).await?;
+ Ok(())
+ }
+ ThemeLineage::Profile {
+ tenant_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ } => {
+ validate_tenant(state, tenant_id)?;
+ validate_org(state, org_id).await?;
+ let key_store = validate_merchant_and_get_key_store(state, org_id, merchant_id).await?;
+ validate_profile(state, profile_id, merchant_id, &key_store).await?;
+ Ok(())
+ }
+ }
+}
+
+fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserResult<()> {
+ if &state.tenant.tenant_id != tenant_id {
+ return Err(UserErrors::InvalidThemeLineage("tenant_id".to_string()).into());
+ }
+ Ok(())
+}
+
+async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> {
+ state
+ .store
+ .find_organization_by_org_id(org_id)
+ .await
+ .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))?;
+ Ok(())
+}
+
+async fn validate_merchant_and_get_key_store(
+ state: &SessionState,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+) -> UserResult<MerchantKeyStore> {
+ 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
+ .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(&state.into(), merchant_id, &key_store)
+ .await
+ .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;
+
+ if &merchant_account.organization_id != org_id {
+ return Err(UserErrors::InvalidThemeLineage("merchant_id".to_string()).into());
+ }
+
+ Ok(key_store)
+}
+
+async fn validate_merchant(
+ state: &SessionState,
+ org_id: &id_type::OrganizationId,
+ merchant_id: &id_type::MerchantId,
+) -> UserResult<()> {
+ validate_merchant_and_get_key_store(state, org_id, merchant_id)
+ .await
+ .map(|_| ())
+}
+
+async fn validate_profile(
+ state: &SessionState,
+ profile_id: &id_type::ProfileId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &MerchantKeyStore,
+) -> UserResult<()> {
+ state
+ .store
+ .find_business_profile_by_merchant_id_profile_id(
+ &state.into(),
+ key_store,
+ merchant_id,
+ profile_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))?;
+ Ok(())
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b1488b904be..0330c43aa45 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -483,6 +483,18 @@ pub enum Flow {
ListUsersInLineage,
/// List invitations for user
ListInvitationsForUser,
+ /// Get theme using lineage
+ GetThemeUsingLineage,
+ /// Get theme using theme id
+ GetThemeUsingThemeId,
+ /// Upload file to theme storage
+ UploadFileToThemeStorage,
+ /// Create theme
+ CreateTheme,
+ /// Update theme
+ UpdateTheme,
+ /// Delete theme
+ DeleteTheme,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-11-25T14:04:47Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds APIs to manage themes.
These are the following APIs
1. Create Theme
2. Delete Theme
3. Update Theme
4. Upload Asset
5. Find Theme by Theme ID
6. Find Theme by Lineage
### Additional Changes
- [x] 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`
7. `crates/router/src/configs`
8. `loadtest/config`
-->
todo!()
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6553
## How did you test 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 Theme
```
curl --location 'http://localhost:8080/user/theme' \
--header 'Content-Type: application/json' \
--header 'api-key: ••••••' \
--data '{
"lineage": {
"entity_type": "profile",
"tenant_id": "t1",
"org_id": "o1",
"merchant_id": "m1",
"profile_id": "p1"
},
"theme_name": "Test",
"theme_data": {
"settings": {
"colors": {
"primary": "#3498db",
"sidebar": "#2ecc71"
},
"buttons": {
"primary": {
"hoverBackgroundColor": "#27ae60"
}
}
}
}
}'
```
2. Delete Theme
```
curl --location --request DELETE 'http://localhost:8080/user/theme/087c79dc-640c-4a2a-8552-6fa4e868cc63?entity_type=profile&tenant_id=t1&org_id=o1&merchant_id=m1&profile_id=p1' \
--header 'api-key: ••••••'
```
3. Update Theme
```
curl --location --request PUT 'http://localhost:8080/user/theme/087c79dc-640c-4a2a-8552-6fa4e868cc63' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"lineage": {
"entity_type": "profile",
"tenant_id": "t1",
"org_id": "o1",
"merchant_id": "m1",
"profile_id": "p1"
},
"theme_data": {
"settings": {
"colors": {
"primary": "#3498xb",
"sidebar": "#2ecc71"
},
"buttons": {
"primary": {
"hoverBackgroundColor": "#27ae60"
}
}
}
}
}'
```
4. Upload Asset
```
curl --location 'http://localhost:8080/user/theme/087c79dc-640c-4a2a-8552-6fa4e868cc63?entity_type=profile&tenant_id=t1&org_id=o1&merchant_id=m1&profile_id=p1' \
--header 'api-key: ••••••' \
--form 'asset_name="logo.png"' \
--form 'asset_data=@"path to file"'
```
5. Get Theme by Theme ID
```
curl --location 'http://localhost:8080/user/theme/087c79dc-640c-4a2a-8552-6fa4e868cc63' \
--header 'api-key: ••••••'
```
6. Get Theme by Lineage
```
curl --location 'http://localhost:8080/user/theme?entity_type=merchant&tenant_id=t1&org_id=o1&merchant_id=m1&profile_id=p1' \
--header 'api-key: ••••••'
```
Responses
- Delete Theme and Upload Asset: 200 OK
- Everything else
```
{
"theme_id": "087c79dc-640c-4a2a-8552-6fa4e868cc63",
"theme_name": "Test",
"entity_type": "profile",
"tenant_id": "t1",
"org_id": "o1",
"merchant_id": "m1",
"profile_id": "p1",
"theme_data": {
"settings": {
"colors": {
"primary": "#3498db",
"sidebar": "#2ecc71"
},
"typography": null,
"buttons": {
"primary": {
"backgroundColor": null,
"textColor": null,
"hoverBackgroundColor": "#27ae60"
},
"secondary": null
},
"borders": null,
"spacing": null
},
"urls": null
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
64383915bda5693df1cecf6cc5683e8b9aaef99b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6534
|
Bug: refactor(users): Make `profile_id` in the JWT non-optional
- We kept the `profile_id` in the JWT optional for backwards compatibility.
- Now we have `profile_id` in all the JWT and this field no longer needs to be optional in JWT.
|
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 2496d22447e..ed018cc2381 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -87,7 +87,7 @@ impl UserRole {
user_id: String,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
- profile_id: Option<id_type::ProfileId>,
+ profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
// Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level
@@ -103,7 +103,6 @@ impl UserRole {
.or(dsl::org_id.eq(org_id).and(
dsl::merchant_id
.eq(merchant_id)
- //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
.and(dsl::profile_id.eq(profile_id)),
));
@@ -137,7 +136,6 @@ impl UserRole {
.or(dsl::org_id.eq(org_id).and(
dsl::merchant_id
.eq(merchant_id)
- //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
.and(dsl::profile_id.eq(profile_id)),
));
@@ -160,7 +158,7 @@ impl UserRole {
user_id: String,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
- profile_id: Option<id_type::ProfileId>,
+ profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
// Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level
@@ -176,7 +174,6 @@ impl UserRole {
.or(dsl::org_id.eq(org_id).and(
dsl::merchant_id
.eq(merchant_id)
- //TODO: In case of None, profile_id = NULL its unexpected behaviour, after V1 profile id will not be option
.and(dsl::profile_id.eq(profile_id)),
));
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index aad2537c3d9..4eb4cf5ed2e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -119,9 +119,7 @@ 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)?,
+ profile_id: user_from_token.profile_id,
entity_type: role_info.get_entity_type(),
},
))
@@ -603,7 +601,7 @@ async fn handle_existing_user_invitation(
invitee_user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
@@ -619,7 +617,7 @@ async fn handle_existing_user_invitation(
invitee_user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
@@ -673,10 +671,6 @@ async fn handle_existing_user_invitation(
.await?
}
EntityType::Profile => {
- let profile_id = user_from_token
- .profile_id
- .clone()
- .ok_or(UserErrors::InternalServerError)?;
user_role
.add_entity(domain::ProfileLevel {
tenant_id: user_from_token
@@ -685,7 +679,7 @@ async fn handle_existing_user_invitation(
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
- profile_id: profile_id.clone(),
+ profile_id: user_from_token.profile_id.clone(),
})
.insert_in_v2(state)
.await?
@@ -705,16 +699,10 @@ async fn handle_existing_user_invitation(
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
},
- EntityType::Profile => {
- let profile_id = user_from_token
- .profile_id
- .clone()
- .ok_or(UserErrors::InternalServerError)?;
- email_types::Entity {
- entity_id: profile_id.get_string_repr().to_owned(),
- entity_type: EntityType::Profile,
- }
- }
+ EntityType::Profile => email_types::Entity {
+ entity_id: user_from_token.profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ },
};
let email_contents = email_types::InviteUser {
@@ -812,10 +800,6 @@ async fn handle_new_user_invitation(
.await?
}
EntityType::Profile => {
- let profile_id = user_from_token
- .profile_id
- .clone()
- .ok_or(UserErrors::InternalServerError)?;
user_role
.add_entity(domain::ProfileLevel {
tenant_id: user_from_token
@@ -824,7 +808,7 @@ async fn handle_new_user_invitation(
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
- profile_id: profile_id.clone(),
+ profile_id: user_from_token.profile_id.clone(),
})
.insert_in_v2(state)
.await?
@@ -848,16 +832,10 @@ async fn handle_new_user_invitation(
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
},
- EntityType::Profile => {
- let profile_id = user_from_token
- .profile_id
- .clone()
- .ok_or(UserErrors::InternalServerError)?;
- email_types::Entity {
- entity_id: profile_id.get_string_repr().to_owned(),
- entity_type: EntityType::Profile,
- }
- }
+ EntityType::Profile => email_types::Entity {
+ entity_id: user_from_token.profile_id.get_string_repr().to_owned(),
+ entity_type: EntityType::Profile,
+ },
};
let email_contents = email_types::InviteUser {
@@ -887,7 +865,7 @@ async fn handle_new_user_invitation(
merchant_id: user_from_token.merchant_id.clone(),
org_id: user_from_token.org_id.clone(),
role_id: request.role_id.clone(),
- profile_id: None,
+ profile_id: user_from_token.profile_id.clone(),
tenant_id: user_from_token.tenant_id.clone(),
};
@@ -939,7 +917,7 @@ pub async fn resend_invite(
user.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
@@ -962,7 +940,7 @@ pub async fn resend_invite(
user.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
@@ -1235,10 +1213,7 @@ pub async fn list_user_roles_details(
merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant)
.then_some(&user_from_token.merchant_id),
profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile)
- .then_some(&user_from_token.profile_id)
- .cloned()
- .flatten()
- .as_ref(),
+ .then_some(&user_from_token.profile_id),
entity_id: None,
version: None,
status: None,
@@ -2864,7 +2839,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
request: user_api::SwitchProfileRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
- if user_from_token.profile_id == Some(request.profile_id.clone()) {
+ if user_from_token.profile_id == request.profile_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same profile".to_string(),
)
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 95a8b7d51d1..6641e553fd8 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -161,7 +161,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
@@ -215,7 +215,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
Some(&user_from_token.merchant_id),
- user_from_token.profile_id.as_ref(),
+ Some(&user_from_token.profile_id),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id.clone(),
@@ -234,7 +234,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
@@ -288,7 +288,7 @@ pub async fn update_user_role(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
Some(&user_from_token.merchant_id),
- user_from_token.profile_id.as_ref(),
+ Some(&user_from_token.profile_id),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id,
@@ -475,7 +475,7 @@ pub async fn delete_user_role(
user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
@@ -522,7 +522,7 @@ pub async fn delete_user_role(
user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
@@ -537,7 +537,7 @@ pub async fn delete_user_role(
user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
@@ -584,7 +584,7 @@ pub async fn delete_user_role(
user_from_db.get_user_id(),
&user_from_token.org_id,
&user_from_token.merchant_id,
- user_from_token.profile_id.as_ref(),
+ &user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
@@ -676,17 +676,13 @@ pub async fn list_users_in_lineage(
.await?
}
EntityType::Profile => {
- let Some(profile_id) = user_from_token.profile_id.as_ref() else {
- return Err(UserErrors::JwtProfileIdMissing.into());
- };
-
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),
+ profile_id: Some(&user_from_token.profile_id),
version: None,
limit: None,
},
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 4b99a9c8f3a..57343e66488 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3026,7 +3026,7 @@ impl UserRoleInterface for KafkaStore {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
@@ -3066,7 +3066,7 @@ impl UserRoleInterface for KafkaStore {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 2d9a949879a..e4e564dc9a4 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -45,7 +45,7 @@ pub trait UserRoleInterface {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
@@ -64,7 +64,7 @@ pub trait UserRoleInterface {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
@@ -100,7 +100,7 @@ impl UserRoleInterface for Store {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -109,7 +109,7 @@ impl UserRoleInterface for Store {
user_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
- profile_id.cloned(),
+ profile_id.to_owned(),
version,
)
.await
@@ -146,7 +146,7 @@ impl UserRoleInterface for Store {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -155,7 +155,7 @@ impl UserRoleInterface for Store {
user_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
- profile_id.cloned(),
+ profile_id.to_owned(),
version,
)
.await
@@ -245,7 +245,7 @@ impl UserRoleInterface for MockDb {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
@@ -261,7 +261,7 @@ impl UserRoleInterface for MockDb {
let profile_level_check = user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == Some(merchant_id)
- && user_role.profile_id.as_ref() == profile_id;
+ && user_role.profile_id.as_ref() == Some(profile_id);
// Check if any condition matches and the version matches
if user_role.user_id == user_id
@@ -338,7 +338,7 @@ impl UserRoleInterface for MockDb {
user_id: &str,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
- profile_id: Option<&id_type::ProfileId>,
+ profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
@@ -355,7 +355,7 @@ impl UserRoleInterface for MockDb {
let profile_level_check = role.org_id.as_ref() == Some(org_id)
&& role.merchant_id.as_ref() == Some(merchant_id)
- && role.profile_id.as_ref() == profile_id;
+ && role.profile_id.as_ref() == Some(profile_id);
// Check if the user role matches the conditions and the version matches
role.user_id == user_id
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index a22d6bf1df9..2caffd4d364 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -81,7 +81,7 @@ pub struct AuthenticationDataWithUser {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub user: storage::User,
- pub profile_id: Option<id_type::ProfileId>,
+ pub profile_id: id_type::ProfileId,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -225,7 +225,7 @@ pub struct AuthToken {
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
- pub profile_id: Option<id_type::ProfileId>,
+ pub profile_id: id_type::ProfileId,
pub tenant_id: Option<String>,
}
@@ -237,7 +237,7 @@ impl AuthToken {
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
- profile_id: Option<id_type::ProfileId>,
+ profile_id: id_type::ProfileId,
tenant_id: Option<String>,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
@@ -261,7 +261,7 @@ pub struct UserFromToken {
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
- pub profile_id: Option<id_type::ProfileId>,
+ pub profile_id: id_type::ProfileId,
pub tenant_id: Option<String>,
}
@@ -1734,7 +1734,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
@@ -1916,7 +1916,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
@@ -2030,11 +2030,7 @@ where
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
- if payload
- .profile_id
- .as_ref()
- .is_some_and(|profile_id| *profile_id != self.profile_id)
- {
+ if payload.profile_id != self.profile_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
@@ -2067,7 +2063,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
@@ -2131,30 +2127,14 @@ where
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
- if let Some(ref payload_profile_id) = payload.profile_id {
- if *payload_profile_id != self.profile_id {
- return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
- } else {
- // if both of them are same then proceed with the profile id present in the request
- let auth = AuthenticationData {
- merchant_account: merchant,
- key_store,
- profile_id: Some(self.profile_id.clone()),
- };
- Ok((
- auth.clone(),
- AuthenticationType::MerchantJwt {
- merchant_id: auth.merchant_account.get_id().clone(),
- user_id: Some(payload.user_id),
- },
- ))
- }
+ if payload.profile_id != self.profile_id {
+ return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
} else {
- // if profile_id is not present in the auth_layer itself then no change in behaviour
+ // if both of them are same then proceed with the profile id present in the request
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(self.profile_id.clone()),
};
Ok((
auth.clone(),
@@ -2304,7 +2284,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
auth,
@@ -2440,7 +2420,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
(auth.clone(), payload.user_id.clone()),
@@ -2558,7 +2538,7 @@ where
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
- profile_id: payload.profile_id,
+ profile_id: Some(payload.profile_id),
};
Ok((
auth.clone(),
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 86f10f1ceb7..634c781da7f 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -132,7 +132,7 @@ impl JWTFlow {
.clone()
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found")?,
- Some(profile_id),
+ profile_id,
Some(user_role.tenant_id.clone()),
)
.await
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index c4647907ff9..8a9daefb287 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -100,7 +100,7 @@ pub async fn generate_jwt_auth_token_with_attributes(
role_id,
&state.conf,
org_id,
- Some(profile_id),
+ profile_id,
tenant_id,
)
.await?;
|
2024-11-11T14:12:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Currently `profile_id` in the JWT is optional, this PR makes it non-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).
-->
Closes #6534.
## How did you test 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 is a internal change and it should not affect any APIs.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
98b141c6a00e6435385e1c513b1684d58567ecee
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6528
|
Bug: fix: trustpay eps redirection in cypress
fix: trustpay eps redirection in cypress
they changed it again
|
2024-11-11T10:19:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
Fix EPS Bank Redirect redirection in Cypress.
Closes #6528
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
NIL
## How did you test 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="453" alt="image" src="https://github.com/user-attachments/assets/a712b6c3-74fa-4a41-8eae-3045bc41e3ac">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `prettier . --write`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0a506b1729a27e47543cf24f64fbad08479d8dec
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6526
|
Bug: [FIX] fix response for migration api
Currently there is inconsistent response due to no validations for request body fields for the migration api.
Implementation -
validations such as empty string check for network transaction id and empty object for connector mandate details should be enforced while evaluating the migration response.
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index ad612ed6f3b..f07634060df 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -28,7 +28,7 @@ use common_utils::{
consts,
crypto::{self, Encryptable},
encryption::Encryption,
- ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt},
+ ext_traits::{AsyncExt, BytesExt, ConfigExt, Encode, StringExt, ValueExt},
generate_id, id_type,
request::Request,
type_name,
@@ -55,6 +55,7 @@ use hyperswitch_domain_models::customer::CustomerUpdate;
use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, metrics::add_attributes, tracing};
+use serde_json::json;
use strum::IntoEnumIterator;
use super::{
@@ -381,7 +382,7 @@ pub async fn migrate_payment_method(
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {
let mut req = req;
- let card_details = req.card.as_ref().get_required_value("card")?;
+ let card_details = &req.card.get_required_value("card")?;
let card_number_validation_result =
cards::CardNumber::from_str(card_details.card_number.peek());
@@ -780,17 +781,6 @@ pub async fn skip_locker_call_and_migrate_payment_method(
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();
@@ -810,11 +800,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,
+ connector_mandate_details: connector_mandate_details.clone(),
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::Active,
- network_transaction_id,
+ network_transaction_id: network_transaction_id.clone(),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
@@ -843,6 +833,21 @@ pub async fn skip_locker_call_and_migrate_payment_method(
logger::debug!("Payment method inserted in db");
+ migration_status.network_transaction_id_migrated(
+ network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
+ );
+
+ migration_status.connector_mandate_details_migrated(
+ connector_mandate_details
+ .clone()
+ .and_then(|val| if val == json!({}) { None } else { Some(true) })
+ .or_else(|| {
+ req.connector_mandate_details
+ .clone()
+ .and_then(|val| (!val.0.is_empty()).then_some(false))
+ }),
+ );
+
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
state,
@@ -1166,10 +1171,14 @@ pub async fn get_client_secret_or_add_payment_method_for_migration(
migration_status.connector_mandate_details_migrated(
connector_mandate_details
.clone()
- .map(|_| true)
- .or_else(|| req.connector_mandate_details.clone().map(|_| false)),
+ .and_then(|val| (val != json!({})).then_some(true))
+ .or_else(|| {
+ req.connector_mandate_details
+ .clone()
+ .and_then(|val| (!val.0.is_empty()).then_some(false))
+ }),
);
-
+ //card is not migrated in this case
migration_status.card_migrated(false);
if res.status == enums::PaymentMethodStatus::AwaitingData {
@@ -1722,15 +1731,6 @@ pub async fn save_migration_payment_method(
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() {
@@ -1940,8 +1940,8 @@ pub async fn save_migration_payment_method(
pm_metadata.cloned(),
None,
locker_id,
- connector_mandate_details,
- network_transaction_id,
+ connector_mandate_details.clone(),
+ network_transaction_id.clone(),
merchant_account.storage_scheme,
payment_method_billing_address.map(Into::into),
None,
@@ -1954,6 +1954,20 @@ pub async fn save_migration_payment_method(
}
}
+ migration_status.card_migrated(true);
+ migration_status.network_transaction_id_migrated(
+ network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),
+ );
+
+ migration_status.connector_mandate_details_migrated(
+ connector_mandate_details
+ .and_then(|val| if val == json!({}) { None } else { Some(true) })
+ .or_else(|| {
+ req.connector_mandate_details
+ .and_then(|val| (!val.0.is_empty()).then_some(false))
+ }),
+ );
+
Ok(services::ApplicationResponse::Json(resp))
}
|
2024-11-11T10:06:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
#6300 has inconsistent response due to no validations for each field in migration api request body.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 case - test migration api with empty fields.
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": "",
"payment_method": "card",
"connector_mandate_details": {},
"network_token": {
"network_token_data": {
"network_token_number": " ",
"network_token_exp_month": "12",
"network_token_exp_year": "21"
},
"network_token_requestor_ref_id": ""
}
}'
```
<img width="880" alt="Screenshot 2024-11-11 at 11 43 58 AM" src="https://github.com/user-attachments/assets/27b1f3b6-cfe9-4917-b3e5-db44342df845">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
086115f47379b06185a1753979fc6dd9dc945afd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6532
|
Bug: feat(themes): Setup DB for themes
There should a separate table for themes for storing the `theme_id`s for a particular lineage. This should be the schema:
| org_id | merchant_id | profile_id | theme_id |
| ------ | ----------- | ---------- | -------- |
| o1 | m1 | p1 | t1 |
| o1 | m1 | p2 | t2 |
This will be used for changing theme automatically when user switches any entities.
|
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index ef7a4b847c4..f7cdfd3617b 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -3,6 +3,8 @@ pub mod keymanager;
/// Enum for Authentication Level
pub mod authentication;
+/// Enum for Theme Lineage
+pub mod theme;
use std::{
borrow::Cow,
diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs
new file mode 100644
index 00000000000..a2e6fe4b19c
--- /dev/null
+++ b/crates/common_utils/src/types/theme.rs
@@ -0,0 +1,39 @@
+use crate::id_type;
+
+/// Enum for having all the required lineage for every level.
+/// Currently being used for theme related APIs and queries.
+#[derive(Debug)]
+pub enum ThemeLineage {
+ /// Tenant lineage variant
+ Tenant {
+ /// tenant_id: String
+ tenant_id: String,
+ },
+ /// Org lineage variant
+ Organization {
+ /// tenant_id: String
+ tenant_id: String,
+ /// org_id: OrganizationId
+ org_id: id_type::OrganizationId,
+ },
+ /// Merchant lineage variant
+ Merchant {
+ /// tenant_id: String
+ tenant_id: String,
+ /// org_id: OrganizationId
+ org_id: id_type::OrganizationId,
+ /// merchant_id: MerchantId
+ merchant_id: id_type::MerchantId,
+ },
+ /// Profile lineage variant
+ Profile {
+ /// tenant_id: String
+ tenant_id: String,
+ /// org_id: OrganizationId
+ org_id: id_type::OrganizationId,
+ /// merchant_id: MerchantId
+ merchant_id: id_type::MerchantId,
+ /// profile_id: ProfileId
+ profile_id: id_type::ProfileId,
+ },
+}
diff --git a/crates/diesel_models/src/query/user.rs b/crates/diesel_models/src/query/user.rs
index 2bd403a847b..1f6e16702fb 100644
--- a/crates/diesel_models/src/query/user.rs
+++ b/crates/diesel_models/src/query/user.rs
@@ -1,6 +1,8 @@
use common_utils::pii;
use diesel::{associations::HasTable, ExpressionMethods};
+
pub mod sample_data;
+pub mod theme;
use crate::{
query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult,
diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs
new file mode 100644
index 00000000000..c021edca325
--- /dev/null
+++ b/crates/diesel_models/src/query/user/theme.rs
@@ -0,0 +1,95 @@
+use common_utils::types::theme::ThemeLineage;
+use diesel::{
+ associations::HasTable,
+ pg::Pg,
+ sql_types::{Bool, Nullable},
+ BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods,
+};
+
+use crate::{
+ query::generics,
+ schema::themes::dsl,
+ user::theme::{Theme, ThemeNew},
+ PgPooledConn, StorageResult,
+};
+
+impl ThemeNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl Theme {
+ fn lineage_filter(
+ lineage: ThemeLineage,
+ ) -> Box<
+ dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>>
+ + 'static,
+ > {
+ match lineage {
+ ThemeLineage::Tenant { tenant_id } => Box::new(
+ dsl::tenant_id
+ .eq(tenant_id)
+ .and(dsl::org_id.is_null())
+ .and(dsl::merchant_id.is_null())
+ .and(dsl::profile_id.is_null())
+ .nullable(),
+ ),
+ ThemeLineage::Organization { tenant_id, org_id } => Box::new(
+ dsl::tenant_id
+ .eq(tenant_id)
+ .and(dsl::org_id.eq(org_id))
+ .and(dsl::merchant_id.is_null())
+ .and(dsl::profile_id.is_null()),
+ ),
+ ThemeLineage::Merchant {
+ tenant_id,
+ org_id,
+ merchant_id,
+ } => Box::new(
+ dsl::tenant_id
+ .eq(tenant_id)
+ .and(dsl::org_id.eq(org_id))
+ .and(dsl::merchant_id.eq(merchant_id))
+ .and(dsl::profile_id.is_null()),
+ ),
+ ThemeLineage::Profile {
+ tenant_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ } => Box::new(
+ dsl::tenant_id
+ .eq(tenant_id)
+ .and(dsl::org_id.eq(org_id))
+ .and(dsl::merchant_id.eq(merchant_id))
+ .and(dsl::profile_id.eq(profile_id)),
+ ),
+ }
+ }
+
+ pub async fn find_by_lineage(
+ conn: &PgPooledConn,
+ lineage: ThemeLineage,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ Self::lineage_filter(lineage),
+ )
+ .await
+ }
+
+ pub async fn delete_by_theme_id_and_lineage(
+ conn: &PgPooledConn,
+ theme_id: String,
+ lineage: ThemeLineage,
+ ) -> StorageResult<Self> {
+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::theme_id
+ .eq(theme_id)
+ .and(Self::lineage_filter(lineage)),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e2ab676b2d3..17de01b1862 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1262,6 +1262,26 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ themes (theme_id) {
+ #[max_length = 64]
+ theme_id -> Varchar,
+ #[max_length = 64]
+ tenant_id -> Varchar,
+ #[max_length = 64]
+ org_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ merchant_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
+ created_at -> Timestamp,
+ last_modified_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1406,6 +1426,7 @@ diesel::allow_tables_to_appear_in_same_query!(
reverse_lookup,
roles,
routing_algorithm,
+ themes,
unified_translations,
user_authentication_methods,
user_key_store,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 3bd31f5cbf3..7b4ccee2c4b 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1208,6 +1208,26 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ themes (theme_id) {
+ #[max_length = 64]
+ theme_id -> Varchar,
+ #[max_length = 64]
+ tenant_id -> Varchar,
+ #[max_length = 64]
+ org_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ merchant_id -> Nullable<Varchar>,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
+ created_at -> Timestamp,
+ last_modified_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1353,6 +1373,7 @@ diesel::allow_tables_to_appear_in_same_query!(
reverse_lookup,
roles,
routing_algorithm,
+ themes,
unified_translations,
user_authentication_methods,
user_key_store,
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 9f7b77dc5d6..cf584c09b12 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -6,8 +6,9 @@ use time::PrimitiveDateTime;
use crate::{diesel_impl::OptionalDieselArray, enums::TotpStatus, schema::users};
pub mod dashboard_metadata;
-
pub mod sample_data;
+pub mod theme;
+
#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
#[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))]
pub struct User {
diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs
new file mode 100644
index 00000000000..0824ae71919
--- /dev/null
+++ b/crates/diesel_models/src/user/theme.rs
@@ -0,0 +1,29 @@
+use common_utils::id_type;
+use diesel::{Identifiable, Insertable, Queryable, Selectable};
+use time::PrimitiveDateTime;
+
+use crate::schema::themes;
+
+#[derive(Clone, Debug, Identifiable, Queryable, Selectable)]
+#[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))]
+pub struct Theme {
+ pub theme_id: String,
+ pub tenant_id: String,
+ pub org_id: Option<id_type::OrganizationId>,
+ pub merchant_id: Option<id_type::MerchantId>,
+ pub profile_id: Option<id_type::ProfileId>,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
+#[diesel(table_name = themes)]
+pub struct ThemeNew {
+ pub theme_id: String,
+ pub tenant_id: String,
+ pub org_id: Option<id_type::OrganizationId>,
+ pub merchant_id: Option<id_type::MerchantId>,
+ pub profile_id: Option<id_type::ProfileId>,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified_at: PrimitiveDateTime,
+}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 81319ae4c0b..377253e9735 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -145,6 +145,7 @@ pub trait GlobalStorageInterface:
+ dyn_clone::DynClone
+ user::UserInterface
+ user_key_store::UserKeyStoreInterface
+ + user::theme::ThemeInterface
+ 'static
{
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 4b99a9c8f3a..d7d283819e5 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1,7 +1,11 @@
use std::sync::Arc;
use common_enums::enums::MerchantStorageScheme;
-use common_utils::{errors::CustomResult, id_type, pii, types::keymanager::KeyManagerState};
+use common_utils::{
+ errors::CustomResult,
+ id_type, pii,
+ types::{keymanager::KeyManagerState, theme::ThemeLineage},
+};
use diesel_models::{
enums,
enums::ProcessTrackerStatus,
@@ -34,7 +38,7 @@ use time::PrimitiveDateTime;
use super::{
dashboard_metadata::DashboardMetadataInterface,
role::RoleInterface,
- user::{sample_data::BatchSampleDataInterface, UserInterface},
+ user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface},
@@ -3683,3 +3687,30 @@ impl UserAuthenticationMethodInterface for KafkaStore {
.await
}
}
+
+#[async_trait::async_trait]
+impl ThemeInterface for KafkaStore {
+ async fn insert_theme(
+ &self,
+ theme: storage::theme::ThemeNew,
+ ) -> CustomResult<storage::theme::Theme, errors::StorageError> {
+ self.diesel_store.insert_theme(theme).await
+ }
+
+ async fn find_theme_by_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::theme::Theme, errors::StorageError> {
+ self.diesel_store.find_theme_by_lineage(lineage).await
+ }
+
+ async fn delete_theme_by_lineage_and_theme_id(
+ &self,
+ theme_id: String,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::theme::Theme, errors::StorageError> {
+ self.diesel_store
+ .delete_theme_by_lineage_and_theme_id(theme_id, lineage)
+ .await
+ }
+}
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 3cf68551b52..14bed15fa45 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -11,6 +11,7 @@ use crate::{
services::Store,
};
pub mod sample_data;
+pub mod theme;
#[async_trait::async_trait]
pub trait UserInterface {
diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs
new file mode 100644
index 00000000000..d71b82cdea4
--- /dev/null
+++ b/crates/router/src/db/user/theme.rs
@@ -0,0 +1,203 @@
+use common_utils::types::theme::ThemeLineage;
+use diesel_models::user::theme as storage;
+use error_stack::report;
+
+use super::MockDb;
+use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ services::Store,
+};
+
+#[async_trait::async_trait]
+pub trait ThemeInterface {
+ async fn insert_theme(
+ &self,
+ theme: storage::ThemeNew,
+ ) -> CustomResult<storage::Theme, errors::StorageError>;
+
+ async fn find_theme_by_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError>;
+
+ async fn delete_theme_by_lineage_and_theme_id(
+ &self,
+ theme_id: String,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl ThemeInterface for Store {
+ async fn insert_theme(
+ &self,
+ theme: storage::ThemeNew,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ theme
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ async fn find_theme_by_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Theme::find_by_lineage(&conn, lineage)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ async fn delete_theme_by_lineage_and_theme_id(
+ &self,
+ theme_id: String,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::Theme::delete_by_theme_id_and_lineage(&conn, theme_id, lineage)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+}
+
+fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool {
+ match lineage {
+ ThemeLineage::Tenant { tenant_id } => {
+ &theme.tenant_id == tenant_id
+ && theme.org_id.is_none()
+ && theme.merchant_id.is_none()
+ && theme.profile_id.is_none()
+ }
+ ThemeLineage::Organization { tenant_id, org_id } => {
+ &theme.tenant_id == tenant_id
+ && theme
+ .org_id
+ .as_ref()
+ .is_some_and(|org_id_inner| org_id_inner == org_id)
+ && theme.merchant_id.is_none()
+ && theme.profile_id.is_none()
+ }
+ ThemeLineage::Merchant {
+ tenant_id,
+ org_id,
+ merchant_id,
+ } => {
+ &theme.tenant_id == tenant_id
+ && theme
+ .org_id
+ .as_ref()
+ .is_some_and(|org_id_inner| org_id_inner == org_id)
+ && theme
+ .merchant_id
+ .as_ref()
+ .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
+ && theme.profile_id.is_none()
+ }
+ ThemeLineage::Profile {
+ tenant_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ } => {
+ &theme.tenant_id == tenant_id
+ && theme
+ .org_id
+ .as_ref()
+ .is_some_and(|org_id_inner| org_id_inner == org_id)
+ && theme
+ .merchant_id
+ .as_ref()
+ .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id)
+ && theme
+ .profile_id
+ .as_ref()
+ .is_some_and(|profile_id_inner| profile_id_inner == profile_id)
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl ThemeInterface for MockDb {
+ async fn insert_theme(
+ &self,
+ new_theme: storage::ThemeNew,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let mut themes = self.themes.lock().await;
+ for theme in themes.iter() {
+ if new_theme.theme_id == theme.theme_id {
+ return Err(errors::StorageError::DuplicateValue {
+ entity: "theme_id",
+ key: None,
+ }
+ .into());
+ }
+
+ if new_theme.tenant_id == theme.tenant_id
+ && new_theme.org_id == theme.org_id
+ && new_theme.merchant_id == theme.merchant_id
+ && new_theme.profile_id == theme.profile_id
+ {
+ return Err(errors::StorageError::DuplicateValue {
+ entity: "lineage",
+ key: None,
+ }
+ .into());
+ }
+ }
+
+ let theme = storage::Theme {
+ theme_id: new_theme.theme_id,
+ tenant_id: new_theme.tenant_id,
+ org_id: new_theme.org_id,
+ merchant_id: new_theme.merchant_id,
+ profile_id: new_theme.profile_id,
+ created_at: new_theme.created_at,
+ last_modified_at: new_theme.last_modified_at,
+ };
+ themes.push(theme.clone());
+
+ Ok(theme)
+ }
+
+ async fn find_theme_by_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let themes = self.themes.lock().await;
+ themes
+ .iter()
+ .find(|theme| check_theme_with_lineage(theme, &lineage))
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "Theme with lineage {:?} not found",
+ lineage
+ ))
+ .into(),
+ )
+ }
+
+ async fn delete_theme_by_lineage_and_theme_id(
+ &self,
+ theme_id: String,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let mut themes = self.themes.lock().await;
+ let index = themes
+ .iter()
+ .position(|theme| {
+ theme.theme_id == theme_id && check_theme_with_lineage(theme, &lineage)
+ })
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "Theme with id {} and lineage {:?} not found",
+ theme_id, lineage
+ )))?;
+
+ let theme = themes.remove(index);
+
+ Ok(theme)
+ }
+}
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index b3358d898b2..efcce567727 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -60,6 +60,7 @@ pub struct MockDb {
pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
pub user_authentication_methods:
Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>,
+ pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>,
}
impl MockDb {
@@ -105,6 +106,7 @@ impl MockDb {
roles: Default::default(),
user_key_store: Default::default(),
user_authentication_methods: Default::default(),
+ themes: Default::default(),
})
}
}
diff --git a/migrations/2024-11-06-121933_setup-themes-table/down.sql b/migrations/2024-11-06-121933_setup-themes-table/down.sql
new file mode 100644
index 00000000000..4b590c34705
--- /dev/null
+++ b/migrations/2024-11-06-121933_setup-themes-table/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+DROP INDEX IF EXISTS themes_index;
+DROP TABLE IF EXISTS themes;
diff --git a/migrations/2024-11-06-121933_setup-themes-table/up.sql b/migrations/2024-11-06-121933_setup-themes-table/up.sql
new file mode 100644
index 00000000000..3d84fcd8140
--- /dev/null
+++ b/migrations/2024-11-06-121933_setup-themes-table/up.sql
@@ -0,0 +1,17 @@
+-- Your SQL goes here
+CREATE TABLE IF NOT EXISTS themes (
+ theme_id VARCHAR(64) PRIMARY KEY,
+ tenant_id VARCHAR(64) NOT NULL,
+ org_id VARCHAR(64),
+ merchant_id VARCHAR(64),
+ profile_id VARCHAR(64),
+ created_at TIMESTAMP NOT NULL,
+ last_modified_at TIMESTAMP NOT NULL
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS themes_index ON themes (
+ tenant_id,
+ COALESCE(org_id, '0'),
+ COALESCE(merchant_id, '0'),
+ COALESCE(profile_id, '0')
+);
|
2024-11-11T12:08:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR creates a new table named `themes` in the DB. This will be used to store the `theme_id` for any lineage of `tenant_id`, `org_id`, `merchant_id` and `profile_id`.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #6532
## How did you test 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 is an internal change and there is no API to test this currently.
I've tested the read query by creating a temporary API which uses the query created in this PR.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6513
|
Bug: docs(analytics): Instructions to set up `currency_conversion` (third party dependency API)
## Requirements
After the changes by [this](#6418) PR, we need to update the documentation for `analytics` crate setup process.
## Reason
Due to the third party dependency on `currency_conversion` crate, we need to ensure the proper setup of this service as well.
|
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md
index 96218fc231c..eb5c26a6ba3 100644
--- a/crates/analytics/docs/README.md
+++ b/crates/analytics/docs/README.md
@@ -91,6 +91,44 @@ source = "kafka"
After making this change, save the file and restart your application for the changes to take effect.
+## Setting up Forex APIs
+
+To use Forex services, you need to sign up and get your API keys from the following providers:
+
+1. Primary Service
+ - Sign up for a free account and get your Primary API key [here](https://openexchangerates.org/).
+ - It will be in dashboard, labeled as `app_id`.
+
+2. Fallback Service
+ - Sign up for a free account and get your Fallback API key [here](https://apilayer.com/marketplace/exchangerate_host-api).
+ - It will be in dashboard, labeled as `access key`.
+
+### Configuring Forex APIs
+
+To configure the Forex APIs, update the `config/development.toml` or `config/docker_compose.toml` file with your API keys:
+
+```toml
+[forex_api]
+api_key = "YOUR API KEY HERE" # Replace the placeholder with your Primary API Key
+fallback_api_key = "YOUR API KEY HERE" # Replace the placeholder with your Fallback API Key
+```
+### Important Note
+```bash
+ERROR router::services::api: error: {"error":{"type":"api","message":"Failed to fetch currency exchange rate","code":"HE_00"}}
+│
+├─▶ Failed to fetch currency exchange rate
+│
+╰─▶ Could not acquire the lock for cache entry
+```
+
+_If you get the above error after setting up, simply remove the `redis` key `"{forex_cache}_lock"` by running this in shell_
+
+```bash
+redis-cli del "{forex_cache}_lock"
+```
+
+After making these changes, save the file and restart your application for the changes to take effect.
+
## Enabling Data Features in Dashboard
To check the data features in the dashboard, you need to enable them in the `config/dashboard.toml` configuration file.
|
2024-11-08T08:27:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Now that `analytics` depends on `currency_conversion` crate after this [PR](#6418), we need to include instructions in `analytics` documentation to set up this service.
## Fixes #6513
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This is related to the PR #6418 and documents the necessary prerequisite setup info.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a5ac69d1a77e772e430df8c4187942de44f23079
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6518
|
Bug: get apple pay certificates only from metadata during the session call
Currently we have apple pay certificates being stored in the `metadata` as well as `connector_wallet_details` when a merchant connector account is created. During the session call we try to get the certificates from the `connector_wallet_details` if it fails we try to get it from `metadata`.
Currently when apple pay certificates are being updated with the merchant connector update call only the metadata is being updated. Because of this `connector_wallet_details` will still have the old data using which we make the session call.
In order to fix it, this pr contains the changes to get the `apple pay certificates` from the `metadata` only as it will have the latest updated data. In subsequent pr mca update inconsistency will be handled.
|
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index ba8054696a1..545d05e776f 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -189,20 +189,11 @@ async fn create_applepay_session_token(
)
} else {
// Get the apple pay metadata
- let connector_apple_pay_wallet_details =
- helpers::get_applepay_metadata(router_data.connector_wallets_details.clone())
- .map_err(|error| {
- logger::debug!(
- "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}",
- error
- )
- })
- .ok();
-
- let apple_pay_metadata = match connector_apple_pay_wallet_details {
- Some(apple_pay_wallet_details) => apple_pay_wallet_details,
- None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?,
- };
+ let apple_pay_metadata =
+ helpers::get_applepay_metadata(router_data.connector_meta_data.clone())
+ .attach_printable(
+ "Failed to to fetch apple pay certificates during session call",
+ )?;
// Get payment request data , apple pay session request and merchant keys
let (
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 5a8bc5cd12b..acaccccbb17 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4788,32 +4788,17 @@ pub fn validate_customer_access(
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
- connector_wallets_details: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
- let connector_apple_pay_wallet_details =
- get_applepay_metadata(connector_wallets_details)
- .map_err(|error| {
- logger::debug!(
- "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
- connector_name,
- error
- )
- })
- .ok();
-
- let option_apple_pay_metadata = match connector_apple_pay_wallet_details {
- Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details),
- None => get_applepay_metadata(connector_metadata)
- .map_err(|error| {
- logger::debug!(
- "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
+ let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
+ .map_err(|error| {
+ logger::info!(
+ "Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
- })
- .ok(),
- };
+ })
+ .ok();
// return true only if the apple flow type is simplified
Ok(matches!(
@@ -4999,7 +4984,6 @@ where
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
- merchant_connector_account_type.get_connector_wallets_details(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
@@ -5027,10 +5011,6 @@ where
for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata.clone(),
- merchant_connector_account
- .connector_wallets_details
- .as_deref()
- .cloned(),
Some(&merchant_connector_account.connector_name),
)? {
let connector_data = api::ConnectorData::get_connector_by_name(
|
2024-11-08T07:44:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently we have apple pay certificates being stored in the `metadata` as well as `connector_wallet_details` when a merchant connector account is created. During the session call we try to get the certificates from the `connector_wallet_details` if it fails we try to get it from `metadata`.
Currently when apple pay certificates are being updated with the merchant connector update call only the metadata is being updated. Because of this `connector_wallet_details` will still have the old data using which we make the session call.
In order to fix it, this pr contains the changes to get the `apple pay certificates` from the `metadata` only as it will have the latest updated data. In subsequent pr mca update inconsistency will be handled.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 apple pay enabled (pass the certificates only in the metadata)
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_1mlXU5snhPhX9lzhh489Hafi6psrvNuTYGqgB7IWO10tUN81hYwfxqr54iHN9LqM' \
--data-raw '{
"amount": 6100,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6100,
"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",
"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_id": "pay_13yS6rPTfz2flIVwTdOD",
"merchant_id": "merchant_1731058139",
"status": "requires_payment_method",
"amount": 6100,
"net_amount": 6100,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI",
"created": "2024-11-08T09:29:43.101Z",
"currency": "USD",
"customer_id": null,
"customer": {
"id": null,
"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": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": null,
"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": null,
"connector_label": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_qk2Nf6soRabKK4PTZPI7",
"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-11-08T09:44:43.101Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-08T09:29:43.156Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Make a session call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_8f588c72e93146fd85d7888b57813cae' \
--data '{
"payment_id": "pay_13yS6rPTfz2flIVwTdOD",
"wallets": [],
"client_secret": "pay_13yS6rPTfz2flIVwTdOD_secret_LDRqGrN0l1Oepne0sswI"
}'
```
```
{
"payment_id": "pay_9dkYqqMjqhB6HVEdmtH8",
"client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0",
"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": "61.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-9dkYqqMjqhB6HVEdmtH8",
"merchant": {
"name": "Hyperswitch",
"url": null,
"country_code": "IN"
},
"amount": {
"option": "FORMAT_TOTAL_PRICE_ONLY",
"currency_code": "USD",
"total": "61.00"
},
"protocol": "PROTOCOL3DS",
"allowed_brands": [
"visa",
"masterCard",
"amex",
"discover"
]
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1731058299555,
"expires_at": 1731061899555,
"merchant_session_identifier": "SSH56D7E29D55C14575B8A72585526E9989_7E0DD1295E42A30B376B18CB4E6B9B9FB4C5E36B3EDF9FB0DEA51F9419420173",
"nonce": "bee270b5",
"merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8",
"domain_name": "hyperswitch-demo-store.netlify.app",
"display_name": "Shankar",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333133395a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420a43222765aad8e37be22057b06a5ff6b4a889b86eb254c8388ecfeb483bd2d20300a06082a8648ce3d04030204473045022005d15b2d109fff00c1f25743f54b973fc0868648bdfde0a53cb08c1b9f618dca022100b68baa956928c8ef13aeadf335868abefabd1ca358e546901d0a53961018187d000000000000",
"operational_analytics_identifier": "Shankar:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8",
"retries": 0,
"psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "61.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.test.fb"
},
"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
}
]
}
```
-> Now update the mca with different apple pay session data and make the session call
```
{
"payment_id": "pay_9dkYqqMjqhB6HVEdmtH8",
"client_secret": "pay_9dkYqqMjqhB6HVEdmtH8_secret_yLYrfUXwlbhz1WTcwAZ0",
"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": "61.00"
},
"delayed_session_token": false,
"connector": "cybersource",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
},
{
"wallet_name": "apple_pay",
"session_token_data": {
"epoch_timestamp": 1731058447406,
"expires_at": 1731062047406,
"merchant_session_identifier": "SSH9AE703AD4E89431CA6995DEB16AECED6_A0E617ED4A56A343E07C6E1255BD4098423B3A8E1243236462D07B14B4A0F7C3",
"nonce": "1ccfd4d4",
"merchant_identifier": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8",
"domain_name": "hyperswitch-demo-store.netlify.app",
"display_name": "hyperswitch",
"signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018830820184020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313130383039333430375a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420aba73465373dde2c582d797f825db72d3cc16bde7b453859381fbe56ea62a66b300a06082a8648ce3d040302044730450221008c76d246dbd8929261aea7a0035b005213d065c8a3ac66339e66ecacdfc589e202200360ac83bb14a1954cfe02f0aef3213d3310a3fef863894bb47e21cea2a39631000000000000",
"operational_analytics_identifier": "hyperswitch:A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8",
"retries": 0,
"psp_id": "A73398AA267417BF8F26F7168B22908662D517F8FF2FC31C76CBF7511F572AB8"
},
"payment_request_data": {
"country_code": "US",
"currency_code": "USD",
"total": {
"label": "applepay",
"type": "final",
"amount": "61.00"
},
"merchant_capabilities": [
"supports3DS"
],
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_identifier": "merchant.test.fb"
},
"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
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a5ac69d1a77e772e430df8c4187942de44f23079
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6521
|
Bug: [FEATURE]: [KLARNA] Klarna Kustom Checkout Integration
### Feature Description
Klarna supports two types of payment methods:
1. Klarna Payments
2. Klarna Kustom Checkout
This issue includes integration of Klarna KCO
### Possible Implementation
Based on the PML got, there will be a switching between both Klarna Payments and Klarna Checkout. Klarna Checkout will include the complete checkout process along with payment.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
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 ee5654cfb6b..f86998cfc6f 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -11766,70 +11766,6 @@
}
}
},
- "OrderDetails": {
- "type": "object",
- "required": [
- "product_name",
- "quantity"
- ],
- "properties": {
- "product_name": {
- "type": "string",
- "description": "Name of the product that is being purchased",
- "example": "shirt",
- "maxLength": 255
- },
- "quantity": {
- "type": "integer",
- "format": "int32",
- "description": "The quantity of the product to be purchased",
- "example": 1,
- "minimum": 0
- },
- "requires_shipping": {
- "type": "boolean",
- "nullable": true
- },
- "product_img_link": {
- "type": "string",
- "description": "The image URL of the product",
- "nullable": true
- },
- "product_id": {
- "type": "string",
- "description": "ID of the product that is being purchased",
- "nullable": true
- },
- "category": {
- "type": "string",
- "description": "Category of the product that is being purchased",
- "nullable": true
- },
- "sub_category": {
- "type": "string",
- "description": "Sub category of the product that is being purchased",
- "nullable": true
- },
- "brand": {
- "type": "string",
- "description": "Brand of the product that is being purchased",
- "nullable": true
- },
- "product_type": {
- "allOf": [
- {
- "$ref": "#/components/schemas/ProductType"
- }
- ],
- "nullable": true
- },
- "product_tax_code": {
- "type": "string",
- "description": "The tax code for the product",
- "nullable": true
- }
- }
- },
"OrderDetailsWithAmount": {
"type": "object",
"required": [
@@ -11852,7 +11788,21 @@
"minimum": 0
},
"amount": {
- "$ref": "#/components/schemas/MinorUnit"
+ "type": "integer",
+ "format": "int64",
+ "description": "the amount per quantity of product"
+ },
+ "tax_rate": {
+ "type": "number",
+ "format": "double",
+ "description": "tax rate applicable to the product",
+ "nullable": true
+ },
+ "total_tax_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "total tax amount applicable to the product",
+ "nullable": true
},
"requires_shipping": {
"type": "boolean",
@@ -12265,6 +12215,17 @@
}
}
},
+ {
+ "type": "object",
+ "required": [
+ "klarna_checkout"
+ ],
+ "properties": {
+ "klarna_checkout": {
+ "type": "object"
+ }
+ }
+ },
{
"type": "object",
"required": [
@@ -12398,6 +12359,13 @@
"description": "The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,",
"example": 6540
},
+ "order_tax_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The payment attempt tax_amount.",
+ "example": 6540,
+ "nullable": true
+ },
"currency": {
"allOf": [
{
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 2464cdf62db..57b15cf0af1 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -731,6 +731,10 @@ pub struct PaymentsRequest {
// Makes the field mandatory in PaymentsCreateRequest
pub amount: Option<Amount>,
+ /// Total tax amount applicable to the order
+ #[schema(value_type = Option<i64>, example = 6540)]
+ pub order_tax_amount: Option<MinorUnit>,
+
/// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars
#[schema(example = "USD", value_type = Option<Currency>)]
#[mandatory_in(PaymentsCreateRequest = Currency)]
@@ -1298,6 +1302,9 @@ pub struct PaymentAttemptResponse {
/// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
+ /// The payment attempt tax_amount.
+ #[schema(value_type = Option<i64>, example = 6540)]
+ pub order_tax_amount: Option<MinorUnit>,
/// The currency of the amount of the payment attempt
#[schema(value_type = Option<Currency>, example = "USD")]
pub currency: Option<enums::Currency>,
@@ -1848,6 +1855,7 @@ pub enum PayLaterData {
/// The token for the sdk workflow
token: String,
},
+ KlarnaCheckout {},
/// For Affirm redirect as PayLater Option
AffirmRedirect {},
/// For AfterpayClearpay redirect as PayLater Option
@@ -1905,6 +1913,7 @@ impl GetAddressFromPaymentMethodData for PayLaterData {
| Self::WalleyRedirect {}
| Self::AlmaRedirect {}
| Self::KlarnaSdk { .. }
+ | Self::KlarnaCheckout {}
| Self::AffirmRedirect {}
| Self::AtomeRedirect {} => None,
}
@@ -2366,6 +2375,7 @@ impl GetPaymentMethodType for PayLaterData {
match self {
Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,
Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,
+ Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna,
Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,
Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,
Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,
@@ -5461,7 +5471,7 @@ pub struct PaymentsRetrieveRequest {
pub expand_attempts: Option<bool>,
}
-#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
#[schema(max_length = 255, example = "shirt")]
@@ -5470,7 +5480,13 @@ pub struct OrderDetailsWithAmount {
#[schema(example = 1)]
pub quantity: u16,
/// the amount per quantity of product
+ #[schema(value_type = i64)]
pub amount: MinorUnit,
+ /// tax rate applicable to the product
+ pub tax_rate: Option<f64>,
+ /// total tax amount applicable to the product
+ #[schema(value_type = Option<i64>)]
+ pub total_tax_amount: Option<MinorUnit>,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
@@ -5491,32 +5507,6 @@ pub struct OrderDetailsWithAmount {
impl masking::SerializableSecret for OrderDetailsWithAmount {}
-#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
-pub struct OrderDetails {
- /// Name of the product that is being purchased
- #[schema(max_length = 255, example = "shirt")]
- pub product_name: String,
- /// The quantity of the product to be purchased
- #[schema(example = 1)]
- pub quantity: u16,
- // Does the order include shipping
- pub requires_shipping: Option<bool>,
- /// The image URL of the product
- pub product_img_link: Option<String>,
- /// ID of the product that is being purchased
- pub product_id: Option<String>,
- /// Category of the product that is being purchased
- pub category: Option<String>,
- /// Sub category of the product that is being purchased
- pub sub_category: Option<String>,
- /// Brand of the product that is being purchased
- pub brand: Option<String>,
- /// Type of the product that is being purchased
- pub product_type: Option<ProductType>,
- /// The tax code for the product
- pub product_tax_code: Option<String>,
-}
-
#[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct RedirectResponse {
#[schema(value_type = Option<String>)]
diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs
index 94f1fa8d266..6562abab4d6 100644
--- a/crates/diesel_models/src/types.rs
+++ b/crates/diesel_models/src/types.rs
@@ -30,6 +30,10 @@ pub struct OrderDetailsWithAmount {
pub product_type: Option<common_enums::ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
+ /// tax rate applicable to the product
+ pub tax_rate: Option<f64>,
+ /// total tax amount applicable to the product
+ pub total_tax_amount: Option<MinorUnit>,
}
impl masking::SerializableSecret for OrderDetailsWithAmount {}
diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
index 479abf13b13..a60e8bdc79e 100644
--- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
@@ -746,6 +746,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
email: Some(match paylater {
PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?,
PayLaterData::KlarnaSdk { token: _ }
+ | PayLaterData::KlarnaCheckout {}
| PayLaterData::AffirmRedirect {}
| PayLaterData::AfterpayClearpayRedirect {}
| PayLaterData::PayBrightRedirect {}
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index 08ca9a54fa4..5abc93b3f88 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -85,6 +85,7 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ
PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
+ | PayLaterData::KlarnaCheckout {}
| PayLaterData::AffirmRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
index 7a30a434a5d..41dc60f8248 100644
--- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
@@ -751,6 +751,7 @@ impl TryFrom<&PayLaterData> for ZenPaymentsRequest {
match value {
PayLaterData::KlarnaRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
+ | PayLaterData::KlarnaCheckout {}
| PayLaterData::AffirmRedirect {}
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect {}
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 6dce48e6996..cf32d966e05 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -2092,6 +2092,7 @@ pub enum PaymentMethodDataType {
SwishQr,
KlarnaRedirect,
KlarnaSdk,
+ KlarnaCheckout,
AffirmRedirect,
AfterpayClearpayRedirect,
PayBrightRedirect,
@@ -2216,6 +2217,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType {
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
+ payment_method_data::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout,
payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 0e8722644bd..6e353afd399 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -133,6 +133,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW
brand,
product_type,
product_tax_code,
+ tax_rate,
+ total_tax_amount,
} = from;
Self {
product_name,
@@ -146,6 +148,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW
brand,
product_type,
product_tax_code,
+ tax_rate,
+ total_tax_amount,
}
}
@@ -162,6 +166,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW
brand,
product_type,
product_tax_code,
+ tax_rate,
+ total_tax_amount,
} = self;
ApiOrderDetailsWithAmount {
product_name,
@@ -175,6 +181,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW
brand,
product_type,
product_tax_code,
+ tax_rate,
+ total_tax_amount,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index db35766f33a..0ca2338926a 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -155,6 +155,7 @@ pub enum CardRedirectData {
pub enum PayLaterData {
KlarnaRedirect {},
KlarnaSdk { token: String },
+ KlarnaCheckout {},
AffirmRedirect {},
AfterpayClearpayRedirect {},
PayBrightRedirect {},
@@ -896,6 +897,7 @@ impl From<api_models::payments::PayLaterData> for PayLaterData {
match value {
api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
+ api_models::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout {},
api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect {}
@@ -1549,6 +1551,7 @@ impl GetPaymentMethodType for PayLaterData {
match self {
Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,
Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,
+ Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna,
Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,
Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,
Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 2f68b481d88..0e25e195c73 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -29,6 +29,7 @@ pub struct PaymentsAuthorizeData {
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
+ pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 7ad5645e75a..91466761009 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -378,7 +378,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::NoonData,
- api_models::payments::OrderDetails,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 5a5454e2505..deb5e7900f2 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -340,7 +340,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::NoonData,
- api_models::payments::OrderDetails,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 16cab2fda47..6e7663a35b7 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2321,7 +2321,8 @@ impl
check_required_field(billing_address, "billing")?;
Ok(AdyenPaymentMethod::Atome)
}
- domain::payments::PayLaterData::KlarnaSdk { .. } => {
+ domain::payments::PayLaterData::KlarnaCheckout {}
+ | domain::payments::PayLaterData::KlarnaSdk { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index d2bdaae0493..77e2a027d83 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -448,7 +448,24 @@ impl
let endpoint =
build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
- Ok(format!("{endpoint}ordermanagement/v1/orders/{order_id}"))
+ let payment_experience = req.request.payment_experience;
+
+ match payment_experience {
+ Some(common_enums::PaymentExperience::InvokeSdkClient) => {
+ Ok(format!("{endpoint}ordermanagement/v1/orders/{order_id}"))
+ }
+ Some(common_enums::PaymentExperience::RedirectToUrl) => {
+ Ok(format!("{endpoint}checkout/v3/orders/{order_id}"))
+ }
+ None => Err(error_stack::report!(errors::ConnectorError::NotSupported {
+ message: "payment_experience not supported".to_string(),
+ connector: "klarna",
+ })),
+ _ => Err(error_stack::report!(errors::ConnectorError::NotSupported {
+ message: "payment_experience not supported".to_string(),
+ connector: "klarna",
+ })),
+ }
}
fn build_request(
@@ -653,6 +670,122 @@ impl
})),
}
}
+ domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => {
+ match (payment_experience, payment_method_type) {
+ (
+ common_enums::PaymentExperience::RedirectToUrl,
+ common_enums::PaymentMethodType::Klarna,
+ ) => Ok(format!("{endpoint}checkout/v3/orders",)),
+ (
+ common_enums::PaymentExperience::DisplayQrCode
+ | common_enums::PaymentExperience::DisplayWaitScreen
+ | common_enums::PaymentExperience::InvokePaymentApp
+ | common_enums::PaymentExperience::InvokeSdkClient
+ | common_enums::PaymentExperience::LinkWallet
+ | common_enums::PaymentExperience::OneClick
+ | common_enums::PaymentExperience::RedirectToUrl
+ | common_enums::PaymentExperience::CollectOtp,
+ common_enums::PaymentMethodType::Ach
+ | common_enums::PaymentMethodType::Affirm
+ | common_enums::PaymentMethodType::AfterpayClearpay
+ | common_enums::PaymentMethodType::Alfamart
+ | common_enums::PaymentMethodType::AliPay
+ | common_enums::PaymentMethodType::AliPayHk
+ | common_enums::PaymentMethodType::Alma
+ | common_enums::PaymentMethodType::ApplePay
+ | common_enums::PaymentMethodType::Atome
+ | common_enums::PaymentMethodType::Bacs
+ | common_enums::PaymentMethodType::BancontactCard
+ | common_enums::PaymentMethodType::Becs
+ | common_enums::PaymentMethodType::Benefit
+ | common_enums::PaymentMethodType::Bizum
+ | common_enums::PaymentMethodType::Blik
+ | common_enums::PaymentMethodType::Boleto
+ | common_enums::PaymentMethodType::BcaBankTransfer
+ | common_enums::PaymentMethodType::BniVa
+ | common_enums::PaymentMethodType::BriVa
+ | common_enums::PaymentMethodType::CardRedirect
+ | common_enums::PaymentMethodType::CimbVa
+ | common_enums::PaymentMethodType::ClassicReward
+ | common_enums::PaymentMethodType::Credit
+ | common_enums::PaymentMethodType::CryptoCurrency
+ | common_enums::PaymentMethodType::Cashapp
+ | common_enums::PaymentMethodType::Dana
+ | common_enums::PaymentMethodType::DanamonVa
+ | common_enums::PaymentMethodType::Debit
+ | common_enums::PaymentMethodType::DirectCarrierBilling
+ | common_enums::PaymentMethodType::Efecty
+ | common_enums::PaymentMethodType::Eps
+ | common_enums::PaymentMethodType::Evoucher
+ | common_enums::PaymentMethodType::Giropay
+ | common_enums::PaymentMethodType::Givex
+ | common_enums::PaymentMethodType::GooglePay
+ | common_enums::PaymentMethodType::GoPay
+ | common_enums::PaymentMethodType::Gcash
+ | common_enums::PaymentMethodType::Ideal
+ | common_enums::PaymentMethodType::Interac
+ | common_enums::PaymentMethodType::Indomaret
+ | common_enums::PaymentMethodType::Klarna
+ | common_enums::PaymentMethodType::KakaoPay
+ | common_enums::PaymentMethodType::MandiriVa
+ | common_enums::PaymentMethodType::Knet
+ | common_enums::PaymentMethodType::MbWay
+ | common_enums::PaymentMethodType::MobilePay
+ | common_enums::PaymentMethodType::Momo
+ | common_enums::PaymentMethodType::MomoAtm
+ | common_enums::PaymentMethodType::Multibanco
+ | common_enums::PaymentMethodType::LocalBankRedirect
+ | common_enums::PaymentMethodType::OnlineBankingThailand
+ | common_enums::PaymentMethodType::OnlineBankingCzechRepublic
+ | common_enums::PaymentMethodType::OnlineBankingFinland
+ | common_enums::PaymentMethodType::OnlineBankingFpx
+ | common_enums::PaymentMethodType::OnlineBankingPoland
+ | common_enums::PaymentMethodType::OnlineBankingSlovakia
+ | common_enums::PaymentMethodType::Oxxo
+ | common_enums::PaymentMethodType::PagoEfectivo
+ | common_enums::PaymentMethodType::PermataBankTransfer
+ | common_enums::PaymentMethodType::OpenBankingUk
+ | common_enums::PaymentMethodType::PayBright
+ | common_enums::PaymentMethodType::Paypal
+ | common_enums::PaymentMethodType::Paze
+ | common_enums::PaymentMethodType::Pix
+ | common_enums::PaymentMethodType::PaySafeCard
+ | common_enums::PaymentMethodType::Przelewy24
+ | common_enums::PaymentMethodType::Pse
+ | common_enums::PaymentMethodType::RedCompra
+ | common_enums::PaymentMethodType::RedPagos
+ | common_enums::PaymentMethodType::SamsungPay
+ | common_enums::PaymentMethodType::Sepa
+ | common_enums::PaymentMethodType::Sofort
+ | common_enums::PaymentMethodType::Swish
+ | common_enums::PaymentMethodType::TouchNGo
+ | common_enums::PaymentMethodType::Trustly
+ | common_enums::PaymentMethodType::Twint
+ | common_enums::PaymentMethodType::UpiCollect
+ | common_enums::PaymentMethodType::UpiIntent
+ | common_enums::PaymentMethodType::Venmo
+ | common_enums::PaymentMethodType::Vipps
+ | common_enums::PaymentMethodType::Walley
+ | common_enums::PaymentMethodType::WeChatPay
+ | common_enums::PaymentMethodType::SevenEleven
+ | common_enums::PaymentMethodType::Lawson
+ | common_enums::PaymentMethodType::LocalBankTransfer
+ | common_enums::PaymentMethodType::MiniStop
+ | common_enums::PaymentMethodType::FamilyMart
+ | common_enums::PaymentMethodType::Seicomart
+ | common_enums::PaymentMethodType::PayEasy
+ | common_enums::PaymentMethodType::Mifinity
+ | common_enums::PaymentMethodType::Fps
+ | common_enums::PaymentMethodType::DuitNow
+ | common_enums::PaymentMethodType::PromptPay
+ | common_enums::PaymentMethodType::VietQr
+ | common_enums::PaymentMethodType::OpenBankingPIS,
+ ) => Err(error_stack::report!(errors::ConnectorError::NotSupported {
+ message: payment_method_type.to_string(),
+ connector: "klarna",
+ })),
+ }
+ }
domain::PaymentMethodData::Card(_)
| domain::PaymentMethodData::CardRedirect(_)
@@ -726,7 +859,7 @@ impl
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: klarna::KlarnaPaymentsResponse = res
+ let response: klarna::KlarnaAuthResponse = res
.response
.parse_struct("KlarnaPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 803dc4a428d..0826b0f2665 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -1,7 +1,9 @@
use api_models::payments;
use common_utils::{pii, types::MinorUnit};
use error_stack::{report, ResultExt};
-use hyperswitch_domain_models::router_data::KlarnaSdkResponse;
+use hyperswitch_domain_models::{
+ router_data::KlarnaSdkResponse, router_response_types::RedirectForm,
+};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -10,7 +12,7 @@ use crate::{
self, AddressData, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData,
},
core::errors,
- types::{self, api, storage::enums, transformers::ForeignFrom},
+ types::{self, api, domain, storage::enums, transformers::ForeignFrom},
};
#[derive(Debug, Serialize)]
@@ -61,9 +63,29 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for KlarnaConnectorMetadataObject {
}
}
-#[derive(Default, Debug, Serialize)]
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum PaymentMethodSpecifics {
+ KlarnaCheckout(KlarnaCheckoutRequestData),
+ KlarnaSdk,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct MerchantURLs {
+ terms: String,
+ checkout: String,
+ confirmation: String,
+ push: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct KlarnaCheckoutRequestData {
+ merchant_urls: MerchantURLs,
+ options: CheckoutOptions,
+}
+
+#[derive(Default, Debug, Deserialize, Serialize)]
pub struct KlarnaPaymentsRequest {
- auto_capture: bool,
order_lines: Vec<OrderLines>,
order_amount: MinorUnit,
purchase_country: enums::CountryAlpha2,
@@ -71,15 +93,32 @@ pub struct KlarnaPaymentsRequest {
merchant_reference1: Option<String>,
merchant_reference2: Option<String>,
shipping_address: Option<KlarnaShippingAddress>,
+ auto_capture: Option<bool>,
+ order_tax_amount: Option<MinorUnit>,
+ #[serde(flatten)]
+ payment_method_specifics: Option<PaymentMethodSpecifics>,
}
#[derive(Debug, Deserialize, Serialize)]
-pub struct KlarnaPaymentsResponse {
+#[serde(untagged)]
+pub enum KlarnaAuthResponse {
+ KlarnaPaymentsAuthResponse(PaymentsResponse),
+ KlarnaCheckoutAuthResponse(CheckoutResponse),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PaymentsResponse {
order_id: String,
fraud_status: KlarnaFraudStatus,
authorized_payment_method: Option<AuthorizedPaymentMethod>,
}
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CheckoutResponse {
+ order_id: String,
+ status: KlarnaCheckoutStatus,
+ html_snippet: String,
+}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthorizedPaymentMethod {
#[serde(rename = "type")]
@@ -106,7 +145,7 @@ pub struct KlarnaSessionRequest {
shipping_address: Option<KlarnaShippingAddress>,
}
-#[derive(Debug, Serialize)]
+#[derive(Debug, Serialize, Deserialize)]
pub struct KlarnaShippingAddress {
city: String,
country: enums::CountryAlpha2,
@@ -120,6 +159,10 @@ pub struct KlarnaShippingAddress {
street_address2: Option<Secret<String>>,
}
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct CheckoutOptions {
+ auto_capture: bool,
+}
#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaSessionResponse {
pub client_token: Secret<String>,
@@ -149,6 +192,8 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsSessionRouterData>> for KlarnaSes
quantity: data.quantity,
unit_price: data.amount,
total_amount: data.amount * data.quantity,
+ total_tax_amount: None,
+ tax_rate: None,
})
.collect(),
shipping_address: get_address_info(item.router_data.get_optional_shipping())
@@ -190,29 +235,100 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP
item: &KlarnaRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let request = &item.router_data.request;
- match request.order_details.clone() {
- Some(order_details) => Ok(Self {
- purchase_country: item.router_data.get_billing_country()?,
- purchase_currency: request.currency,
- order_amount: item.amount,
- order_lines: order_details
- .iter()
- .map(|data| OrderLines {
- name: data.product_name.clone(),
- quantity: data.quantity,
- unit_price: data.amount,
- total_amount: data.amount * data.quantity,
- })
- .collect(),
- merchant_reference1: Some(item.router_data.connector_request_reference_id.clone()),
- merchant_reference2: item.router_data.request.merchant_order_reference_id.clone(),
- auto_capture: request.is_auto_capture()?,
- shipping_address: get_address_info(item.router_data.get_optional_shipping())
- .transpose()?,
- }),
- None => Err(report!(errors::ConnectorError::MissingRequiredField {
- field_name: "order_details"
- })),
+ let payment_method_data = request.payment_method_data.clone();
+ let return_url = item.router_data.request.get_return_url()?;
+ let webhook_url = item.router_data.request.get_webhook_url()?;
+ match payment_method_data {
+ domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaSdk { .. }) => {
+ match request.order_details.clone() {
+ Some(order_details) => Ok(Self {
+ purchase_country: item.router_data.get_billing_country()?,
+ purchase_currency: request.currency,
+ order_amount: item.amount,
+ order_lines: order_details
+ .iter()
+ .map(|data| OrderLines {
+ name: data.product_name.clone(),
+ quantity: data.quantity,
+ unit_price: data.amount,
+ total_amount: data.amount * data.quantity,
+ total_tax_amount: None,
+ tax_rate: None,
+ })
+ .collect(),
+ merchant_reference1: Some(
+ item.router_data.connector_request_reference_id.clone(),
+ ),
+ merchant_reference2: item
+ .router_data
+ .request
+ .merchant_order_reference_id
+ .clone(),
+ auto_capture: Some(request.is_auto_capture()?),
+ shipping_address: get_address_info(
+ item.router_data.get_optional_shipping(),
+ )
+ .transpose()?,
+ order_tax_amount: None,
+ payment_method_specifics: None,
+ }),
+ None => Err(report!(errors::ConnectorError::MissingRequiredField {
+ field_name: "order_details"
+ })),
+ }
+ }
+ domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => {
+ match request.order_details.clone() {
+ Some(order_details) => Ok(Self {
+ purchase_country: item.router_data.get_billing_country()?,
+ purchase_currency: request.currency,
+ order_amount: item.amount
+ - request.order_tax_amount.unwrap_or(MinorUnit::zero()),
+ order_tax_amount: request.order_tax_amount,
+ order_lines: order_details
+ .iter()
+ .map(|data| OrderLines {
+ name: data.product_name.clone(),
+ quantity: data.quantity,
+ unit_price: data.amount,
+ total_amount: data.amount * data.quantity,
+ total_tax_amount: data.total_tax_amount,
+ tax_rate: data.tax_rate,
+ })
+ .collect(),
+ payment_method_specifics: Some(PaymentMethodSpecifics::KlarnaCheckout(
+ KlarnaCheckoutRequestData {
+ merchant_urls: MerchantURLs {
+ terms: return_url.clone(),
+ checkout: return_url.clone(),
+ confirmation: return_url,
+ push: webhook_url,
+ },
+ options: CheckoutOptions {
+ auto_capture: request.is_auto_capture()?,
+ },
+ },
+ )),
+ shipping_address: get_address_info(
+ item.router_data.get_optional_shipping(),
+ )
+ .transpose()?,
+ merchant_reference1: Some(
+ item.router_data.connector_request_reference_id.clone(),
+ ),
+ merchant_reference2: item
+ .router_data
+ .request
+ .merchant_order_reference_id
+ .clone(),
+ auto_capture: None,
+ }),
+ None => Err(report!(errors::ConnectorError::MissingRequiredField {
+ field_name: "order_details"
+ })),
+ }
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
@@ -240,53 +356,82 @@ fn get_address_info(
})
}
-impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
+impl TryFrom<types::PaymentsResponseRouterData<KlarnaAuthResponse>>
for types::PaymentsAuthorizeRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
+
fn try_from(
- item: types::PaymentsResponseRouterData<KlarnaPaymentsResponse>,
+ item: types::PaymentsResponseRouterData<KlarnaAuthResponse>,
) -> Result<Self, Self::Error> {
- let connector_response = types::ConnectorResponseData::with_additional_payment_method_data(
- match item.response.authorized_payment_method {
- Some(authorized_payment_method) => {
- types::AdditionalPaymentMethodConnectorResponse::from(authorized_payment_method)
- }
- None => {
- types::AdditionalPaymentMethodConnectorResponse::PayLater { klarna_sdk: None }
- }
- },
- );
-
- Ok(Self {
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- item.response.order_id.clone(),
- ),
- redirection_data: Box::new(None),
- mandate_reference: Box::new(None),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: Some(item.response.order_id.clone()),
- incremental_authorization_allowed: None,
- charge_id: None,
+ match item.response {
+ KlarnaAuthResponse::KlarnaPaymentsAuthResponse(ref response) => {
+ let connector_response =
+ response
+ .authorized_payment_method
+ .as_ref()
+ .map(|authorized_payment_method| {
+ types::ConnectorResponseData::with_additional_payment_method_data(
+ types::AdditionalPaymentMethodConnectorResponse::from(
+ authorized_payment_method.clone(),
+ ),
+ )
+ });
+
+ Ok(Self {
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.order_id.clone(),
+ ),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(response.order_id.clone()),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ status: enums::AttemptStatus::foreign_from((
+ response.fraud_status.clone(),
+ item.data.request.is_auto_capture()?,
+ )),
+ connector_response,
+ ..item.data
+ })
+ }
+ KlarnaAuthResponse::KlarnaCheckoutAuthResponse(ref response) => Ok(Self {
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.order_id.clone(),
+ ),
+ redirection_data: Box::new(Some(RedirectForm::Html {
+ html_data: response.html_snippet.clone(),
+ })),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(response.order_id.clone()),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ status: enums::AttemptStatus::foreign_from((
+ response.status.clone(),
+ item.data.request.is_auto_capture()?,
+ )),
+ connector_response: None,
+ ..item.data
}),
- status: enums::AttemptStatus::foreign_from((
- item.response.fraud_status,
- item.data.request.is_auto_capture()?,
- )),
- connector_response: Some(connector_response),
- ..item.data
- })
+ }
}
}
-
-#[derive(Debug, Serialize)]
+#[derive(Default, Debug, Serialize, Deserialize)]
pub struct OrderLines {
name: String,
quantity: u16,
unit_price: MinorUnit,
total_amount: MinorUnit,
+ total_tax_amount: Option<MinorUnit>,
+ tax_rate: Option<f64>,
}
#[derive(Debug, Serialize)]
@@ -325,6 +470,13 @@ pub enum KlarnaFraudStatus {
Rejected,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum KlarnaCheckoutStatus {
+ CheckoutComplete,
+ CheckoutIncomplete,
+}
+
impl ForeignFrom<(KlarnaFraudStatus, bool)> for enums::AttemptStatus {
fn foreign_from((klarna_status, is_auto_capture): (KlarnaFraudStatus, bool)) -> Self {
match klarna_status {
@@ -341,13 +493,42 @@ impl ForeignFrom<(KlarnaFraudStatus, bool)> for enums::AttemptStatus {
}
}
+impl ForeignFrom<(KlarnaCheckoutStatus, bool)> for enums::AttemptStatus {
+ fn foreign_from((klarna_status, is_auto_capture): (KlarnaCheckoutStatus, bool)) -> Self {
+ match klarna_status {
+ KlarnaCheckoutStatus::CheckoutIncomplete => {
+ if is_auto_capture {
+ Self::AuthenticationPending
+ } else {
+ Self::Authorized
+ }
+ }
+ KlarnaCheckoutStatus::CheckoutComplete => Self::Charged,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum KlarnaPsyncResponse {
+ KlarnaSDKPsyncResponse(KlarnaSDKSyncResponse),
+ KlarnaCheckoutPSyncResponse(KlarnaCheckoutSyncResponse),
+}
+
#[derive(Debug, Serialize, Deserialize)]
-pub struct KlarnaPsyncResponse {
+pub struct KlarnaSDKSyncResponse {
pub order_id: String,
pub status: KlarnaPaymentStatus,
pub klarna_reference: Option<String>,
}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct KlarnaCheckoutSyncResponse {
+ pub order_id: String,
+ pub status: KlarnaCheckoutStatus,
+ pub options: CheckoutOptions,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum KlarnaPaymentStatus {
@@ -379,25 +560,45 @@ impl<F, T>
fn try_from(
item: types::ResponseRouterData<F, KlarnaPsyncResponse, T, types::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(),
- ),
- redirection_data: Box::new(None),
- mandate_reference: Box::new(None),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: item
- .response
- .klarna_reference
- .or(Some(item.response.order_id)),
- incremental_authorization_allowed: None,
- charge_id: None,
+ match item.response {
+ KlarnaPsyncResponse::KlarnaSDKPsyncResponse(response) => Ok(Self {
+ status: enums::AttemptStatus::from(response.status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.order_id.clone(),
+ ),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: response
+ .klarna_reference
+ .or(Some(response.order_id.clone())),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
}),
- ..item.data
- })
+ KlarnaPsyncResponse::KlarnaCheckoutPSyncResponse(response) => Ok(Self {
+ status: enums::AttemptStatus::foreign_from((
+ response.status.clone(),
+ response.options.auto_capture,
+ )),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response.order_id.clone(),
+ ),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(response.order_id.clone()),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ }
}
}
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 121ec1d7b7c..a4195655ed3 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -977,6 +977,7 @@ where
get_pay_later_info(AlternativePaymentMethodType::AfterPay, item)
}
domain::PayLaterData::KlarnaSdk { .. }
+ | domain::PayLaterData::KlarnaCheckout {}
| domain::PayLaterData::AffirmRedirect {}
| domain::PayLaterData::PayBrightRedirect {}
| domain::PayLaterData::WalleyRedirect {}
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 11e01b78e13..600b7ab0e22 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1256,6 +1256,7 @@ impl TryFrom<&domain::PayLaterData> for PaypalPaymentsRequest {
match value {
domain::PayLaterData::KlarnaRedirect { .. }
| domain::PayLaterData::KlarnaSdk { .. }
+ | domain::PayLaterData::KlarnaCheckout {}
| domain::PayLaterData::AffirmRedirect {}
| domain::PayLaterData::AfterpayClearpayRedirect { .. }
| domain::PayLaterData::PayBrightRedirect {}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 2f0b0e0316f..262b0348b5a 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -992,6 +992,7 @@ impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType {
}
domain::PayLaterData::KlarnaSdk { .. }
+ | domain::PayLaterData::KlarnaCheckout {}
| domain::PayLaterData::PayBrightRedirect {}
| domain::PayLaterData::WalleyRedirect {}
| domain::PayLaterData::AlmaRedirect {}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 1ea7565f69f..171f19bc70a 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -2793,6 +2793,7 @@ pub enum PaymentMethodDataType {
SwishQr,
KlarnaRedirect,
KlarnaSdk,
+ KlarnaCheckout,
AffirmRedirect,
AfterpayClearpayRedirect,
PayBrightRedirect,
@@ -2916,6 +2917,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType {
domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
+ domain::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout,
domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 58217ef3f41..b6abe94f60f 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1477,6 +1477,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
surcharge_amount,
tax_amount,
),
+
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 6a676af47b7..37e129ba707 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1427,6 +1427,15 @@ impl PaymentCreate {
let skip_external_tax_calculation = request.skip_external_tax_calculation;
+ let tax_details = request
+ .order_tax_amount
+ .map(|tax_amount| diesel_models::TaxDetails {
+ default: Some(diesel_models::DefaultTax {
+ order_tax_amount: tax_amount,
+ }),
+ payment_method_type: None,
+ });
+
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_account.get_id().to_owned(),
@@ -1481,7 +1490,7 @@ impl PaymentCreate {
is_payment_processor_token_flow,
organization_id: merchant_account.organization_id.clone(),
shipping_cost: request.shipping_cost,
- tax_details: None,
+ tax_details,
skip_external_tax_calculation,
psd2_sca_exemption_type: request.psd2_sca_exemption_type,
})
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 92486320cde..f6bd3efc555 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -261,6 +261,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(
.net_amount
.get_amount_as_i64(),
minor_amount: payment_data.payment_attempt.amount_details.net_amount,
+ order_tax_amount: None,
currency: payment_data.payment_intent.amount_details.currency,
browser_info: None,
email: None,
@@ -2431,25 +2432,6 @@ pub fn mobile_payment_next_steps_check(
Ok(mobile_payment_next_step)
}
-pub fn change_order_details_to_new_type(
- order_amount: MinorUnit,
- order_details: api_models::payments::OrderDetails,
-) -> Option<Vec<api_models::payments::OrderDetailsWithAmount>> {
- Some(vec![api_models::payments::OrderDetailsWithAmount {
- product_name: order_details.product_name,
- quantity: order_details.quantity,
- amount: order_amount,
- product_img_link: order_details.product_img_link,
- requires_shipping: order_details.requires_shipping,
- product_id: order_details.product_id,
- category: order_details.category,
- sub_category: order_details.sub_category,
- brand: order_details.brand,
- product_type: order_details.product_type,
- product_tax_code: order_details.product_tax_code,
- }])
-}
-
impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::payments::NextActionData {
fn foreign_from(qr_info: api_models::payments::QrCodeInformation) -> Self {
match qr_info {
@@ -2625,6 +2607,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
statement_descriptor: payment_data.payment_intent.statement_descriptor_name,
capture_method: payment_data.payment_attempt.capture_method,
amount: amount.get_amount_as_i64(),
+ order_tax_amount: payment_data
+ .payment_attempt
+ .net_amount
+ .get_order_tax_amount(),
minor_amount: amount,
currency: payment_data.currency,
browser_info,
@@ -2961,7 +2947,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessi
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
-
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let order_tax_amount = payment_data
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 2ab43378516..de4c063c41a 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -873,6 +873,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
+ order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: None,
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 3bd31873131..bd55bd96b96 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -29,6 +29,7 @@ impl VerifyConnectorData {
amount: 1000,
minor_amount: common_utils::types::MinorUnit::new(1000),
confirm: true,
+ order_tax_amount: None,
currency: storage_enums::Currency::USD,
metadata: None,
mandate_id: None,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 269eb831fc6..d10f1686507 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1234,6 +1234,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse {
attempt_id: payment_attempt.attempt_id,
status: payment_attempt.status,
amount: payment_attempt.net_amount.get_order_amount(),
+ order_tax_amount: payment_attempt.net_amount.get_order_tax_amount(),
currency: payment_attempt.currency,
connector: payment_attempt.connector,
error_message: payment_attempt.error_reason,
diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs
index 1994acb6a65..15f980e242e 100644
--- a/crates/router/tests/connectors/payme.rs
+++ b/crates/router/tests/connectors/payme.rs
@@ -90,6 +90,8 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
@@ -391,6 +393,8 @@ async fn should_fail_payment_for_incorrect_cvc() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
@@ -431,6 +435,8 @@ async fn should_fail_payment_for_invalid_exp_month() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
@@ -471,6 +477,8 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
router_return_url: Some("https://hyperswitch.io".to_string()),
webhook_url: Some("https://hyperswitch.io".to_string()),
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index f195aeaf7c4..489b55a227b 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -939,6 +939,7 @@ impl Default for PaymentAuthorizeType {
payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0),
amount: 100,
minor_amount: MinorUnit::new(100),
+ order_tax_amount: Some(MinorUnit::zero()),
currency: enums::Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index de60c5e8d86..a13fe48d255 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -334,6 +334,8 @@ async fn should_fail_payment_for_incorrect_card_number() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
email: Some(Email::from_str("test@gmail.com").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
@@ -377,6 +379,8 @@ async fn should_fail_payment_for_incorrect_cvc() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
email: Some(Email::from_str("test@gmail.com").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
@@ -420,6 +424,8 @@ async fn should_fail_payment_for_invalid_exp_month() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
email: Some(Email::from_str("test@gmail.com").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
@@ -463,6 +469,8 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
brand: None,
product_type: None,
product_tax_code: None,
+ tax_rate: None,
+ total_tax_amount: None,
}]),
email: Some(Email::from_str("test@gmail.com").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
|
2024-12-15T22:10:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Klarna Kustom Checkout (KCO) integration
Klarna provides two payment methods:
1. Klarna Payments (for US)
2. Klarna Kustom Checkout (for EU)
Any one of the methods can be used at a time and switching between Klarna Payments and Klarna Checkout is been done. Based on the PML got, there will be a switching between Klarna Payments and Klarna Checkout.
The redirect_to_url link from response is used to complete the payment.
Linking the original PR here https://github.com/juspay/hyperswitch/pull/6590
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `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).
-->
This PR is related to issue: https://github.com/juspay/hyperswitch/issues/6521
## How did you test it?
I tested it using postman by hitting the required endpoints. Curl to the postman setup:
1. Configure Klarna Checkout for merchant account
```
curl --location 'http://localhost:8080/account/merchant_1734083062/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "payment_processor",
"connector_name": "klarna",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "kl******",
"key1": "2fe*****"
},
"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": "redirect_to_url",
"payment_method_type": "klarna"
}
]
}
],
"metadata": {
"klarna_region": "Europe"
},
"business_country": "FR"
}
'
```
Response:
```
{
"connector_type": "payment_processor",
"connector_name": "klarna",
"connector_label": "klarna_US_default",
"merchant_connector_id": "mca_uscoeTxtbsDsj2b37wv8",
"profile_id": "pro_PdHB9mW2uWUx2di0W9u3",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "kl***********************************************************************************************************************************************************************z0",
"key1": "2f********************************89"
},
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"klarna_region": "Europe"
},
"test_mode": true,
"disabled": false,
"frm_configs": null,
"business_country": "FR",
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active",
"additional_merchant_data": null,
"connector_wallets_details": null
}
```
2. Create a Klarna Checkout Payment request
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_nsmdfKGJM74PYSViFQ04zsoTMLFkF2VkcvuRdmerez2zBfHSjCrZIxpEln9vYBgl' \
--data-raw '{
"amount": 50000,
"order_tax_amount":0,
"confirm": false,
"currency": "EUR",
"capture_method": "automatic",
"customer_id": "klarna",
"payment_experience":"redirect_to_url",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_method_data": {
"pay_later": {
"klarna_checkout":{}
}
},
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"return_url": "https://google.com"
}'
```
Response:
```
{
"payment_id": "pay_b9SVvCHWeHFV7jiTCr1v",
"merchant_id": "merchant_1734083062",
"status": "requires_confirmation",
"amount": 50000,
"net_amount": 50000,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_b9SVvCHWeHFV7jiTCr1v_secret_uTuJ4C4UZtzKWCkJqKyj",
"created": "2024-12-16T12:15:12.009Z",
"currency": "EUR",
"customer_id": "klarna",
"customer": {
"id": "klarna",
"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": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "pay_later",
"payment_method_data": {
"pay_later": {
"klarna_sdk": 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": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "klarna",
"created_at": 1734351311,
"expires": 1734354911,
"secret": "epk_5aaf5ecba75d4de68712573428fe89f2"
},
"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_PdHB9mW2uWUx2di0W9u3",
"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-12-16T12:30:12.009Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-12-16T12:15:12.033Z",
"split_payments": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": 0,
"connector_mandate_id": null
}
```
3. Confirm payment
```
curl --location 'http://localhost:8080/payments/pay_b9SVvCHWeHFV7jiTCr1v/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_nsmdfKGJM74PYSViFQ04zsoTMLFkF2VkcvuRdmerez2zBfHSjCrZIxpEln9vYBgl' \
--data-raw '{
"amount": 50000,
"order_tax_amount":0,
"currency": "EUR",
"amount_to_capture": 50000,
"retry_action": "manual_retry",
"capture_method": "automatic",
"payment_experience":"redirect_to_url",
"profile_id": null,
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"setup_future_usage":"on_session",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"customer_id": "customer123",
"phone_country_code": "+1",
"routing": {
"type": "single",
"data": "stripe"
},
"description": "Its my first payment request",
"return_url": "https://google.com",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_method_data": {
"pay_later": {
"klarna_checkout":{}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "FR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "FR",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"order_details": [
{
"product_name": "Red T-Shirt",
"quantity": 5,
"amount": 10000,
"account_name": "transaction_processing",
"total_tax_amount": 0,
"tax_rate": 0,
"total_amount": 50000
}
],
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"payment_link": false,
"payment_link_config": {
"theme": "",
"logo": "",
"seller_name": "",
"sdk_layout": "",
"display_sdk_only": false,
"enabled_saved_payment_method": false
},
"payment_type": "normal",
"request_incremental_authorization": false,
"merchant_order_reference_id": "test_ord"
}
'
```
Response:
```
{
"payment_id": "pay_FrDhjLjXbKxLYD3Pz2Gj",
"merchant_id": "merchant_1734083062",
"status": "requires_customer_action",
"amount": 50000,
"net_amount": 50000,
"shipping_cost": null,
"amount_capturable": 50000,
"amount_received": null,
"connector": "klarna",
"client_secret": "pay_FrDhjLjXbKxLYD3Pz2Gj_secret_4xESj0dqk8aXuOpHWJTM",
"created": "2024-12-16T12:12:58.052Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "pay_later",
"payment_method_data": {
"pay_later": {
"klarna_sdk": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "FR",
"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": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "FR",
"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": "guest@example.com"
},
"order_details": [
{
"brand": null,
"amount": 10000,
"category": null,
"quantity": 5,
"tax_rate": 0.0,
"product_id": null,
"product_name": "Red T-Shirt",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"total_tax_amount": 0,
"requires_shipping": null
}
],
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_FrDhjLjXbKxLYD3Pz2Gj/merchant_1734083062/pay_FrDhjLjXbKxLYD3Pz2Gj_2"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna",
"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": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"payment_link": null,
"profile_id": "pro_PdHB9mW2uWUx2di0W9u3",
"surcharge_details": null,
"attempt_count": 2,
"merchant_decision": null,
"merchant_connector_id": "mca_uscoeTxtbsDsj2b37wv8",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-12-16T12:27:58.052Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "128.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-12-16T12:13:19.188Z",
"split_payments": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": 0,
"connector_mandate_id": null
}
```
After completing the payment on clicking the redirect_url, PSync response is as follows:
4. PSync:
```
curl --location 'http://localhost:8080/payments/pay_FrDhjLjXbKxLYD3Pz2Gj?force_sync=true&expand_captures=true&expand_attempts=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_nsmdfKGJM74PYSViFQ04zsoTMLFkF2VkcvuRdmerez2zBfHSjCrZIxpEln9vYBgl'
```
Response:
```
{
"payment_id": "pay_FrDhjLjXbKxLYD3Pz2Gj",
"merchant_id": "merchant_1734083062",
"status": "succeeded",
"amount": 50000,
"net_amount": 50000,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": 50000,
"connector": "klarna",
"client_secret": "pay_FrDhjLjXbKxLYD3Pz2Gj_secret_4xESj0dqk8aXuOpHWJTM",
"created": "2024-12-16T12:12:58.052Z",
"currency": "EUR",
"customer_id": "customer123",
"customer": {
"id": "customer123",
"name": "John Doe",
"email": "customer@gmail.com",
"phone": "9999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"attempts": [
{
"attempt_id": "pay_FrDhjLjXbKxLYD3Pz2Gj_1",
"status": "failure",
"amount": 50000,
"order_tax_amount": 0,
"currency": "EUR",
"connector": "klarna",
"error_message": "Bad value: authorization_token",
"payment_method": "pay_later",
"connector_transaction_id": null,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"created_at": "2024-12-16T12:12:58.052Z",
"modified_at": "2024-12-16T12:13:11.833Z",
"cancellation_reason": null,
"mandate_id": null,
"error_code": "BAD_VALUE",
"payment_token": null,
"connector_metadata": null,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna",
"reference_id": null,
"unified_code": "UE_9000",
"unified_message": "Something went wrong",
"client_source": null,
"client_version": null
},
{
"attempt_id": "pay_FrDhjLjXbKxLYD3Pz2Gj_2",
"status": "authentication_pending",
"amount": 50000,
"order_tax_amount": 0,
"currency": "EUR",
"connector": "klarna",
"error_message": null,
"payment_method": "pay_later",
"connector_transaction_id": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"created_at": "2024-12-16T12:13:18.866Z",
"modified_at": "2024-12-16T12:13:19.200Z",
"cancellation_reason": null,
"mandate_id": null,
"error_code": null,
"payment_token": null,
"connector_metadata": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna",
"reference_id": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"unified_code": null,
"unified_message": null,
"client_source": null,
"client_version": null
}
],
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "pay_later",
"payment_method_data": {
"pay_later": {
"klarna_sdk": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "FR",
"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": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "FR",
"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": "guest@example.com"
},
"order_details": [
{
"brand": null,
"amount": 10000,
"category": null,
"quantity": 5,
"tax_rate": 0.0,
"product_id": null,
"product_name": "Red T-Shirt",
"product_type": null,
"sub_category": null,
"product_img_link": null,
"product_tax_code": null,
"total_tax_amount": 0,
"requires_shipping": null
}
],
"email": "customer@gmail.com",
"name": "John Doe",
"phone": "9999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna",
"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": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "abef2bbc-d284-423b-b3fa-6bad31df2c32",
"payment_link": null,
"profile_id": "pro_PdHB9mW2uWUx2di0W9u3",
"surcharge_details": null,
"attempt_count": 2,
"merchant_decision": null,
"merchant_connector_id": "mca_uscoeTxtbsDsj2b37wv8",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-12-16T12:27:58.052Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "128.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_b5F9KF9igKlKRYpGnalg",
"payment_method_status": "inactive",
"updated": "2024-12-16T12:13:57.721Z",
"split_payments": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": 0,
"connector_mandate_id": null
}
```
Please test Klarna SDK also.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
886e2aacd7dcd8a04a33884ceafb1562aa7c365f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6508
|
Bug: [FEATURE] Add support for payout connector integrations for connectors crate
### Feature Description
To be able to support connector integrations in router and the new hyperswitch_connectors crate.
### Possible Implementation
Move payout API traits to a common place - in hyperswitch_interfaces crate.
### 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/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 418d58eb54b..81c079d5d52 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -1049,6 +1049,56 @@ default_imp_for_file_upload!(
connectors::Zsl
);
+macro_rules! default_imp_for_payouts {
+ ($($path:ident::$connector:ident),*) => {
+ $(
+ impl api::Payouts for $path::$connector {}
+ )*
+ };
+}
+
+default_imp_for_payouts!(
+ connectors::Airwallex,
+ connectors::Amazonpay,
+ connectors::Bambora,
+ connectors::Billwerk,
+ connectors::Bitpay,
+ connectors::Cashtocode,
+ connectors::Cryptopay,
+ connectors::Coinbase,
+ connectors::Deutschebank,
+ connectors::Digitalvirgo,
+ connectors::Dlocal,
+ connectors::Elavon,
+ connectors::Fiserv,
+ connectors::Fiservemea,
+ connectors::Fiuu,
+ connectors::Forte,
+ connectors::Globepay,
+ connectors::Helcim,
+ connectors::Jpmorgan,
+ connectors::Mollie,
+ connectors::Multisafepay,
+ connectors::Nexinets,
+ connectors::Nexixpay,
+ connectors::Nomupay,
+ connectors::Novalnet,
+ connectors::Payeezy,
+ connectors::Payu,
+ connectors::Powertranz,
+ connectors::Razorpay,
+ connectors::Shift4,
+ connectors::Square,
+ connectors::Stax,
+ connectors::Taxjar,
+ connectors::Tsys,
+ connectors::Volt,
+ connectors::Worldline,
+ connectors::Worldpay,
+ connectors::Zen,
+ connectors::Zsl
+);
+
#[cfg(feature = "payouts")]
macro_rules! default_imp_for_payouts_create {
($($path:ident::$connector:ident),*) => {
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
index 7205865f24a..0ea8996cb4c 100644
--- a/crates/hyperswitch_interfaces/src/api.rs
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -38,6 +38,8 @@ use masking::Maskable;
use router_env::metrics::add_attributes;
use serde_json::json;
+#[cfg(feature = "payouts")]
+pub use self::payouts::*;
pub use self::{payments::*, refunds::*};
use crate::{
configs::Connectors, connector_integration_v2::ConnectorIntegrationV2, consts, errors,
@@ -410,3 +412,7 @@ pub trait ConnectorRedirectResponse {
Ok(CallConnectorAction::Avoid)
}
}
+
+/// Empty trait for when payouts feature is disabled
+#[cfg(not(feature = "payouts"))]
+pub trait Payouts {}
diff --git a/crates/hyperswitch_interfaces/src/api/payouts.rs b/crates/hyperswitch_interfaces/src/api/payouts.rs
index 894f636707a..5fc0280f19c 100644
--- a/crates/hyperswitch_interfaces/src/api/payouts.rs
+++ b/crates/hyperswitch_interfaces/src/api/payouts.rs
@@ -1,13 +1,15 @@
//! Payouts interface
-use hyperswitch_domain_models::router_flow_types::payouts::{
- PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
-};
-#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
- router_request_types::PayoutsData, router_response_types::PayoutsResponseData,
+ router_flow_types::payouts::{
+ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
+ PoSync,
+ },
+ router_request_types::PayoutsData,
+ router_response_types::PayoutsResponseData,
};
+use super::ConnectorCommon;
use crate::api::ConnectorIntegration;
/// trait PayoutCancel
@@ -42,3 +44,17 @@ pub trait PayoutRecipientAccount:
/// trait PayoutSync
pub trait PayoutSync: ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> {}
+
+/// trait Payouts
+pub trait Payouts:
+ ConnectorCommon
+ + PayoutCancel
+ + PayoutCreate
+ + PayoutEligibility
+ + PayoutFulfill
+ + PayoutQuote
+ + PayoutRecipient
+ + PayoutRecipientAccount
+ + PayoutSync
+{
+}
diff --git a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs
index 40e0726ce80..9027152f02d 100644
--- a/crates/hyperswitch_interfaces/src/api/payouts_v2.rs
+++ b/crates/hyperswitch_interfaces/src/api/payouts_v2.rs
@@ -1,13 +1,15 @@
//! Payouts V2 interface
-use hyperswitch_domain_models::router_flow_types::payouts::{
- PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync,
-};
-#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
- router_data_v2::flow_common_types::PayoutFlowData, router_request_types::PayoutsData,
+ router_data_v2::flow_common_types::PayoutFlowData,
+ router_flow_types::payouts::{
+ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
+ PoSync,
+ },
+ router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
+use super::ConnectorCommon;
use crate::api::ConnectorIntegrationV2;
/// trait PayoutCancelV2
@@ -57,3 +59,21 @@ pub trait PayoutSyncV2:
ConnectorIntegrationV2<PoSync, PayoutFlowData, PayoutsData, PayoutsResponseData>
{
}
+
+/// trait Payouts
+pub trait PayoutsV2:
+ ConnectorCommon
+ + PayoutCancelV2
+ + PayoutCreateV2
+ + PayoutEligibilityV2
+ + PayoutFulfillV2
+ + PayoutQuoteV2
+ + PayoutRecipientV2
+ + PayoutRecipientAccountV2
+ + PayoutSyncV2
+{
+}
+
+/// Empty trait for when payouts feature is disabled
+#[cfg(not(feature = "payouts"))]
+pub trait PayoutsV2 {}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index a6894502996..1358bcedba1 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -12,6 +12,7 @@ pub mod session_update_flow;
pub mod setup_mandate_flow;
use async_trait::async_trait;
+use hyperswitch_interfaces::api::payouts::Payouts;
#[cfg(feature = "frm")]
use crate::types::fraud_check as frm_types;
@@ -969,88 +970,49 @@ default_imp_for_post_processing_steps!(
macro_rules! default_imp_for_payouts {
($($path:ident::$connector:ident),*) => {
$(
- impl api::Payouts for $path::$connector {}
+ impl Payouts for $path::$connector {}
)*
};
}
#[cfg(feature = "dummy_connector")]
-impl<const T: u8> api::Payouts for connector::DummyConnector<T> {}
+impl<const T: u8> Payouts for connector::DummyConnector<T> {}
default_imp_for_payouts!(
connector::Aci,
- connector::Airwallex,
- connector::Amazonpay,
connector::Authorizedotnet,
- connector::Bambora,
connector::Bamboraapac,
connector::Bankofamerica,
- connector::Billwerk,
- connector::Bitpay,
connector::Bluesnap,
connector::Boku,
connector::Braintree,
- connector::Cashtocode,
connector::Checkout,
- connector::Cryptopay,
- connector::Coinbase,
connector::Datatrans,
- connector::Deutschebank,
- connector::Digitalvirgo,
- connector::Dlocal,
- connector::Elavon,
- connector::Fiserv,
- connector::Fiservemea,
- connector::Fiuu,
- connector::Forte,
connector::Globalpay,
- connector::Globepay,
connector::Gocardless,
connector::Gpayments,
- connector::Helcim,
connector::Iatapay,
connector::Itaubank,
- connector::Jpmorgan,
connector::Klarna,
connector::Mifinity,
- connector::Mollie,
- connector::Multisafepay,
connector::Netcetera,
- connector::Nexinets,
- connector::Nexixpay,
connector::Nmi,
- connector::Nomupay,
connector::Noon,
- connector::Novalnet,
connector::Nuvei,
connector::Opayo,
connector::Opennode,
connector::Paybox,
- connector::Payeezy,
connector::Payme,
- connector::Payu,
connector::Placetopay,
connector::Plaid,
- connector::Powertranz,
connector::Prophetpay,
connector::Rapyd,
- connector::Razorpay,
connector::Riskified,
- connector::Shift4,
connector::Signifyd,
- connector::Square,
- connector::Stax,
- connector::Taxjar,
connector::Threedsecureio,
connector::Trustpay,
- connector::Tsys,
- connector::Volt,
connector::Wellsfargo,
- connector::Wellsfargopayout,
- connector::Worldline,
- connector::Worldpay,
- connector::Zen,
- connector::Zsl
+ connector::Wellsfargopayout
);
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index e3c311710d5..985a6644524 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -568,25 +568,6 @@ pub trait FraudCheck {}
#[cfg(not(feature = "frm"))]
pub trait FraudCheckV2 {}
-#[cfg(feature = "payouts")]
-pub trait Payouts:
- ConnectorCommon
- + PayoutCancel
- + PayoutCreate
- + PayoutEligibility
- + PayoutFulfill
- + PayoutQuote
- + PayoutRecipient
- + PayoutRecipientAccount
- + PayoutSync
-{
-}
-#[cfg(not(feature = "payouts"))]
-pub trait Payouts {}
-
-#[cfg(not(feature = "payouts"))]
-pub trait PayoutsV2 {}
-
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs
index a9630beb25a..b5a6ac24ca9 100644
--- a/crates/router/src/types/api/payouts.rs
+++ b/crates/router/src/types/api/payouts.rs
@@ -11,7 +11,7 @@ pub use hyperswitch_domain_models::router_flow_types::payouts::{
};
pub use hyperswitch_interfaces::api::payouts::{
PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient,
- PayoutRecipientAccount, PayoutSync,
+ PayoutRecipientAccount, PayoutSync, Payouts,
};
pub use super::payouts_v2::{
|
2024-11-05T11:21:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #6508
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
This helps us implement new payout connector integrations in `hyperswitch_connectors` crate
## How did you test it?
Not needed as it's only a refactor. New connectors being added in `hyperswitch_connectors` crate can be tested
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
20a3a1c2d6bb93fb4dae7f7eb669ebd85e631c96
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6506
|
Bug: [BUG] API Reference documentation broken
### Bug Description
API reference is broken for following endpoints:
- `API Key - Create`
- `API Key - Revoke`
- `Routing - Retrieve`
- `Routing - Activate Config`
### Expected Behavior
<img width="1514" alt="image" src="https://github.com/user-attachments/assets/139a8e53-1d10-4e60-98c4-a4cb569f3d22">
### Actual Behavior
<img width="1514" alt="image" src="https://github.com/user-attachments/assets/f89e07c1-94a3-4e95-8a19-1c3495138704">
### Steps To Reproduce
Go to https://api-reference.hyperswitch.io/api-reference/api-key/api-key--create
### Context For The Bug
_No response_
### Environment
Web
### 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!
|
2024-11-07T11:04:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Fixed broken API reference for the following endpoints:
- `API Key - Create`
- `API Key - Revoke`
- `Routing - Retrieve`
- `Routing - Activate Config`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cf126b940812b8adce26d7a0f957ed92309130d6
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6505
|
Bug: add card expiry check in the `network_transaction_id_and_card_details` based `MIT` flow
[Reference pr](https://github.com/juspay/hyperswitch/pull/6245).
Add card expiry validation for the `recurring_details` = `network_transaction_id_and_card_details` based MIT flow
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 5d75001b118..a09510a4c4e 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4464,6 +4464,11 @@ where
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")?;
+ helpers::validate_card_expiry(
+ &card_details_for_network_transaction_id.card_exp_month,
+ &card_details_for_network_transaction_id.card_exp_year,
+ )?;
+
let network_transaction_id_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
|
2024-11-07T10:52:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
[Reference pr](https://github.com/juspay/hyperswitch/pull/6245).
Add card expiry validation for the `recurring_details` = `network_transaction_id_and_card_details` based MIT 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
-> Create payment with recurring details "type": "network_transaction_id_and_card_details" with expired card
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: ' \
--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": "11",
"card_exp_year": "2023",
"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"
}
}'
```
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Expiry Year",
"code": "IR_16"
}
}
```
-> Create payment with recurring details "type": "network_transaction_id_and_card_details" with valid card
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: ' \
--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": "11",
"card_exp_year": "2024",
"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_1BG9IxreD8qApunv5xiB",
"merchant_id": "merchant_1730973695",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua",
"created": "2024-11-07T11:04:36.886Z",
"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": "11",
"card_exp_year": "2024",
"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": "7309774770706430804953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_1BG9IxreD8qApunv5xiB_1",
"payment_link": null,
"profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-11-07T11:19:36.886Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-07T11:04:37.995Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Psync
```
curl --location 'http://localhost:8080/payments/pay_1BG9IxreD8qApunv5xiB?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: '
```
```
{
"payment_id": "pay_1BG9IxreD8qApunv5xiB",
"merchant_id": "merchant_1730973695",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_1BG9IxreD8qApunv5xiB_secret_Kwrf2y7DNIo17tGrh4Ua",
"created": "2024-11-07T11:04:36.886Z",
"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": "11",
"card_exp_year": "2024",
"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": "7309774770706430804953",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_1BG9IxreD8qApunv5xiB_1",
"payment_link": null,
"profile_id": "pro_nHm5ZVnwRP6Wixvy0bPZ",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_1Cr87i1MXNK3yoZsjM7q",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-11-07T11:19:36.886Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-07T11:04:37.995Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cf126b940812b8adce26d7a0f957ed92309130d6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6501
|
Bug: feat: implement scylla cql traits for StrongSecret
|
diff --git a/Cargo.lock b/Cargo.lock
index d232fcbf024..2d1f3cf4b06 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3698,6 +3698,12 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "histogram"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12cb882ccb290b8646e554b157ab0b71e64e8d5bef775cd66b6531e52d302669"
+
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -4309,6 +4315,15 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.11"
@@ -4566,6 +4581,15 @@ dependencies = [
"linked-hash-map",
]
+[[package]]
+name = "lz4_flex"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5"
+dependencies = [
+ "twox-hash",
+]
+
[[package]]
name = "masking"
version = "0.1.0"
@@ -4573,6 +4597,7 @@ dependencies = [
"bytes 1.7.1",
"diesel",
"erased-serde 0.4.5",
+ "scylla",
"serde",
"serde_json",
"subtle",
@@ -5970,6 +5995,15 @@ dependencies = [
"getrandom",
]
+[[package]]
+name = "rand_pcg"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e"
+dependencies = [
+ "rand_core",
+]
+
[[package]]
name = "rand_xorshift"
version = "0.3.0"
@@ -6891,6 +6925,66 @@ dependencies = [
"untrusted 0.9.0",
]
+[[package]]
+name = "scylla"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8139623d3fb0c8205b15e84fa587f3aa0ba61f876c19a9157b688f7c1763a7c5"
+dependencies = [
+ "arc-swap",
+ "async-trait",
+ "byteorder",
+ "bytes 1.7.1",
+ "chrono",
+ "dashmap",
+ "futures 0.3.30",
+ "hashbrown 0.14.5",
+ "histogram",
+ "itertools 0.13.0",
+ "lazy_static",
+ "lz4_flex",
+ "rand",
+ "rand_pcg",
+ "scylla-cql",
+ "scylla-macros",
+ "smallvec 1.13.2",
+ "snap",
+ "socket2",
+ "thiserror",
+ "tokio 1.40.0",
+ "tracing",
+ "uuid",
+]
+
+[[package]]
+name = "scylla-cql"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de7020bcd1f6fdbeaed356cd426bf294b2071bd7120d48d2e8e319295e2acdcd"
+dependencies = [
+ "async-trait",
+ "byteorder",
+ "bytes 1.7.1",
+ "lz4_flex",
+ "scylla-macros",
+ "snap",
+ "thiserror",
+ "tokio 1.40.0",
+ "uuid",
+]
+
+[[package]]
+name = "scylla-macros"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3859b6938663fc5062e3b26f3611649c9bd26fb252e85f6fdfa581e0d2ce74b6"
+dependencies = [
+ "darling 0.20.10",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.77",
+]
+
[[package]]
name = "sdd"
version = "3.0.2"
@@ -7314,6 +7408,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "snap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b"
+
[[package]]
name = "socket2"
version = "0.5.7"
@@ -7568,6 +7668,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
[[package]]
name = "storage_impl"
version = "0.1.0"
@@ -8669,6 +8775,16 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "twox-hash"
+version = "1.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"
+dependencies = [
+ "cfg-if 1.0.0",
+ "static_assertions",
+]
+
[[package]]
name = "typeid"
version = "1.0.2"
diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml
index ed20a08de34..425c1ca36ec 100644
--- a/crates/masking/Cargo.toml
+++ b/crates/masking/Cargo.toml
@@ -12,6 +12,7 @@ default = ["alloc", "serde", "diesel", "time"]
alloc = ["zeroize/alloc"]
serde = ["dep:serde", "dep:serde_json"]
time = ["dep:time"]
+cassandra = ["dep:scylla"]
[package.metadata.docs.rs]
all-features = true
@@ -27,6 +28,7 @@ subtle = "2.5.0"
time = { version = "0.3.35", optional = true, features = ["serde-human-readable"] }
url = { version = "2.5.0", features = ["serde"] }
zeroize = { version = "1.7", default-features = false }
+scylla = { version = "0.14.0", optional = true}
[dev-dependencies]
serde_json = "1.0.115"
diff --git a/crates/masking/src/cassandra.rs b/crates/masking/src/cassandra.rs
new file mode 100644
index 00000000000..dc81512e79d
--- /dev/null
+++ b/crates/masking/src/cassandra.rs
@@ -0,0 +1,50 @@
+use scylla::{
+ cql_to_rust::FromCqlVal,
+ deserialize::DeserializeValue,
+ frame::response::result::{ColumnType, CqlValue},
+ serialize::{
+ value::SerializeValue,
+ writers::{CellWriter, WrittenCellProof},
+ SerializationError,
+ },
+};
+
+use crate::{abs::PeekInterface, StrongSecret};
+
+impl<T> SerializeValue for StrongSecret<T>
+where
+ T: SerializeValue + zeroize::Zeroize + Clone,
+{
+ fn serialize<'b>(
+ &self,
+ typ: &ColumnType,
+ writer: CellWriter<'b>,
+ ) -> Result<WrittenCellProof<'b>, SerializationError> {
+ self.peek().serialize(typ, writer)
+ }
+}
+
+impl<'frame, T> DeserializeValue<'frame> for StrongSecret<T>
+where
+ T: DeserializeValue<'frame> + zeroize::Zeroize + Clone,
+{
+ fn type_check(typ: &ColumnType) -> Result<(), scylla::deserialize::TypeCheckError> {
+ T::type_check(typ)
+ }
+
+ fn deserialize(
+ typ: &'frame ColumnType,
+ v: Option<scylla::deserialize::FrameSlice<'frame>>,
+ ) -> Result<Self, scylla::deserialize::DeserializationError> {
+ Ok(Self::new(T::deserialize(typ, v)?))
+ }
+}
+
+impl<T> FromCqlVal<CqlValue> for StrongSecret<T>
+where
+ T: FromCqlVal<CqlValue> + zeroize::Zeroize + Clone,
+{
+ fn from_cql(cql_val: CqlValue) -> Result<Self, scylla::cql_to_rust::FromCqlValError> {
+ Ok(Self::new(T::from_cql(cql_val)?))
+ }
+}
diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs
index ca0da6b6767..d376e935bd6 100644
--- a/crates/masking/src/lib.rs
+++ b/crates/masking/src/lib.rs
@@ -57,6 +57,9 @@ pub mod prelude {
#[cfg(feature = "diesel")]
mod diesel;
+#[cfg(feature = "cassandra")]
+mod cassandra;
+
pub mod maskable;
pub use maskable::*;
|
2024-11-07T06:34:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] New feature
## Description
<!-- Describe your changes in detail -->
This adds `SerializeValue` and `FromCQL` traits for masking StrongSecret
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This is needed for Cassandra ORM to work
## How did you test 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 ENVIRONEMTS **
Compiler guided
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
90d9ffc1d2e13b83931762b05632056520eea07f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6491
|
Bug: feat(analytics): revert remove additional filters from PaymentIntentFilters
When global filters are applied on the dashboard, these filters are being sent to both Payment Attempt and Payment Intent related metrics.
Initially backend support was not present for capturing these filters and adding to the queries, for Payment Intent related metrics, but for the new Analytics V2 dashboard, since the Sessionizer Tables are being used, all these filter fields are supported in the Sessionizer Payment Intents table.
When backend support was added to apply these filters for the new dashboard, the old dashboard started breaking, as the filter fields are not present in the existing Payment Intents table.
FE stopped sending these filters to Payment Intent metrics on the old dashboard, and so we can add these filters back to PaymentIntentFilters to support the filters on the new Analytics V2 dashboard.
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index 3e8915c60a2..42b4895b6a2 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -372,6 +372,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 d03d6c2a15f..1468a67570a 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,5 +54,14 @@ 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>,
pub customer_id: Option<String>,
}
diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs
index 9aa7d3e9771..ee3d4773e24 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -36,6 +36,15 @@ 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>,
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/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs
index 51b574f4ad3..cf733b0c3da 100644
--- a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs
@@ -138,6 +138,15 @@ where
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)?,
diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
index 14e168b3523..07b1bfcf69f 100644
--- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
+++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
@@ -114,6 +114,15 @@ where
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)?,
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
index 644bf35a723..7475a75bb53 100644
--- 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
@@ -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/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
index e7772245063..506965375f5 100644
--- 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
@@ -128,6 +128,15 @@ where
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)?,
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
index eed6bf85a2c..0b55c101a7c 100644
--- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
@@ -113,6 +113,15 @@ where
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)?,
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
index bd1f8bbbcd9..8c340d0b2d6 100644
--- 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
@@ -114,6 +114,15 @@ where
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)?,
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
index 6d36aca5172..8105a4c82a4 100644
--- 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
@@ -122,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/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
index bf97e4c41ef..0b28cb5366d 100644
--- 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
@@ -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/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs
index cea5b2fa465..20ef8be6277 100644
--- 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
@@ -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/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
index b23fcafdee0..8468911f7bb 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -122,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/types.rs b/crates/analytics/src/payment_intents/types.rs
index bb5141297c5..a27ef2d840d 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")?;
+ }
if !self.customer_id.is_empty() {
builder
.add_filter_in_range_clause("customer_id", &self.customer_id)
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 7c90e37c55f..0a641fbc5f9 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -604,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),
@@ -627,6 +666,15 @@ 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,
@@ -652,6 +700,45 @@ 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),
+ })?;
let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e {
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
@@ -660,6 +747,15 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi
status,
currency,
profile_id,
+ connector,
+ authentication_type,
+ payment_method,
+ payment_method_type,
+ card_network,
+ merchant_id,
+ card_last_4,
+ card_issuer,
+ error_reason,
customer_id,
})
}
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index 435e95451fe..fc21bf09819 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -35,6 +35,12 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> {
PaymentIntentDimensions::PaymentIntentStatus,
PaymentIntentDimensions::Currency,
PaymentIntentDimensions::ProfileId,
+ PaymentIntentDimensions::Connector,
+ PaymentIntentDimensions::AuthType,
+ PaymentIntentDimensions::PaymentMethod,
+ PaymentIntentDimensions::PaymentMethodType,
+ PaymentIntentDimensions::CardNetwork,
+ PaymentIntentDimensions::MerchantId,
]
.into_iter()
.map(Into::into)
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 60662f2e90a..ab93fdc4815 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 {
@@ -17,6 +19,24 @@ pub struct PaymentIntentFilters {
#[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>,
+ #[serde(default)]
pub customer_id: Vec<id_type::CustomerId>,
}
@@ -42,6 +62,15 @@ pub enum PaymentIntentDimensions {
PaymentIntentStatus,
Currency,
ProfileId,
+ Connector,
+ AuthType,
+ PaymentMethod,
+ PaymentMethodType,
+ CardNetwork,
+ MerchantId,
+ CardLast4,
+ CardIssuer,
+ ErrorReason,
}
#[derive(
@@ -112,6 +141,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")]
@@ -125,12 +163,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,
}
@@ -142,6 +198,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);
}
}
|
2024-11-06T11:07:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Reverts [https://github.com/juspay/hyperswitch/pull/6403](https://github.com/juspay/hyperswitch/pull/6403)
When global filters are applied on the dashboard, these filters are being sent to both Payment Attempt and Payment Intent related metrics.
Initially backend support was not present for capturing these filters and adding to the queries, for Payment Intent related metrics, but for the new Analytics V2 dashboard, since the Sessionizer Tables are being used, all these filter fields are supported in the Sessionizer Payment Intents table.
When backend support was added to apply these filters for the new dashboard, the old dashboard started breaking, as the filter fields are not present in the existing Payment Intents table.
FE stopped sending these filters to Payment Intent metrics on the old dashboard, and so adding these filters back to PaymentIntentFilters to support the filters on the new Analytics V2 dashboard.
The additional filters added:
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Enable filters for Payment Intent related metrics on the new Analytics V2 dashboard.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Hit the curl:
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDkxNDM0Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.Y7RdCF52kfFCUld587axdN5d4Xl7SGK4wv7C-bdDI0M' \
--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-10-14T18:30:00Z",
"endTime": "2024-10-22T15:24:00Z"
},
"groupByNames": [
"currency"
],
"filters": {
"connector": [
"stripe_test"
]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_total_smart_retries"
]
}
]'
```
We should be able to extract the results based on the additional filters that are applied:
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
01c5216fdd6f1d841082868cccea6054b64e9e07
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6509
|
Bug: [Enhancement] V2: Standardise endpoint naming scheme
Use kebab case for all API endpoints consistently for V2.
i.e. `/v2/like-this` instead of `/v2/not_like_this`
|
diff --git a/api-reference-v2/api-reference/api-key/api-key--create.mdx b/api-reference-v2/api-reference/api-key/api-key--create.mdx
index a92a8ea77fd..abc1dcda10f 100644
--- a/api-reference-v2/api-reference/api-key/api-key--create.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--create.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /v2/api_keys
+openapi: post /v2/api-keys
---
\ No newline at end of file
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
index 5975e9bd6ca..fb84b35fbc7 100644
--- a/api-reference-v2/api-reference/api-key/api-key--list.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/api_keys/list
+openapi: get /v2/api-keys/list
---
diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
index ee7970122d4..72864363357 100644
--- a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/api_keys/{id}
+openapi: get /v2/api-keys/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
index 9362743088b..b7ffd42e449 100644
--- a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
@@ -1,3 +1,3 @@
---
-openapi: delete /v2/api_keys/{id}
+openapi: delete /v2/api-keys/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference-v2/api-reference/api-key/api-key--update.mdx
index c682cf1ee9e..2434e4981fc 100644
--- a/api-reference-v2/api-reference/api-key/api-key--update.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: put /v2/api_keys/{id}
+openapi: put /v2/api-keys/{id}
---
diff --git a/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx
index 6560f45e5fa..93c5a980c27 100644
--- a/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx
+++ b/api-reference-v2/api-reference/business-profile/merchant-connector--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{profile_id}/connector_accounts
+openapi: get /v2/profiles/{profile_id}/connector-accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/connector-account/connector-account--create.mdx b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx
index d8cac2bab39..d672d6fa34d 100644
--- a/api-reference-v2/api-reference/connector-account/connector-account--create.mdx
+++ b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /v2/connector_accounts
+openapi: post /v2/connector-accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx
index 5c959648fff..15fdd664412 100644
--- a/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx
+++ b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx
@@ -1,3 +1,3 @@
---
-openapi: delete /v2/connector_accounts/{id}
+openapi: delete /v2/connector-accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx
index 918de031276..dbd26b9b10b 100644
--- a/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx
+++ b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/connector_accounts/{id}
+openapi: get /v2/connector-accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/connector-account/connector-account--update.mdx b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx
index 6ccd052fb9b..fe864d538f8 100644
--- a/api-reference-v2/api-reference/connector-account/connector-account--update.mdx
+++ b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: put /v2/connector_accounts/{id}
+openapi: put /v2/connector-accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
index 97deb0832cc..069bd602ddf 100644
--- a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
+++ b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/merchant_accounts/{id}/profiles
+openapi: get /v2/merchant-accounts/{id}/profiles
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx
index d870b811aae..38aed603f62 100644
--- a/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx
+++ b/api-reference-v2/api-reference/merchant-account/merchant-account--create.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /v2/merchant_accounts
+openapi: post /v2/merchant-accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx
index d082565234e..3b744fb1406 100644
--- a/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx
+++ b/api-reference-v2/api-reference/merchant-account/merchant-account--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/merchant_accounts/{id}
+openapi: get /v2/merchant-accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx b/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx
index 51f80ceea30..eb2e92d0652 100644
--- a/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx
+++ b/api-reference-v2/api-reference/merchant-account/merchant-account--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: put /v2/merchant_accounts/{id}
+openapi: put /v2/merchant-accounts/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/merchant-account/profile--list.mdx b/api-reference-v2/api-reference/merchant-account/profile--list.mdx
deleted file mode 100644
index e14bc0d6ef3..00000000000
--- a/api-reference-v2/api-reference/merchant-account/profile--list.mdx
+++ /dev/null
@@ -1,3 +0,0 @@
----
-openapi: get /v2/merchant_accounts/{account_id}/profiles
----
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx b/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx
index 58d467dc572..9a03e8713d1 100644
--- a/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx
+++ b/api-reference-v2/api-reference/organization/organization--merchant-account--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/organization/{id}/merchant_accounts
+openapi: get /v2/organization/{id}/merchant-accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx b/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx
new file mode 100644
index 00000000000..7809830b820
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/payments/{id}/saved-payment-methods
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx b/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx
new file mode 100644
index 00000000000..ef5a27f9604
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/list-payment-methods-for-a-customer.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/customers/{id}/saved-payment-methods
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx
new file mode 100644
index 00000000000..134374a7b6c
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--confirm-intent.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/payment-methods/{id}/confirm-intent
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx
new file mode 100644
index 00000000000..42cf716f2ab
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--create-intent.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/payment-methods/create-intent
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx
new file mode 100644
index 00000000000..1dce5179a94
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--create.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /v2/payment-methods
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx
new file mode 100644
index 00000000000..210bf843f97
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--delete.mdx
@@ -0,0 +1,3 @@
+---
+openapi: delete /v2/payment-methods/{id}
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx
new file mode 100644
index 00000000000..957d9760b3f
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--retrieve.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/payment-methods/{id}
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx b/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx
new file mode 100644
index 00000000000..0adee195a6f
--- /dev/null
+++ b/api-reference-v2/api-reference/payment-methods/payment-method--update.mdx
@@ -0,0 +1,3 @@
+---
+openapi: patch /v2/payment-methods/{id}/update-saved-payment-method
+---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
index 81f640436f4..55218be7c0b 100644
--- a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
+++ b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{id}/connector_accounts
+openapi: get /v2/profiles/{id}/connector-accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
index 7225f422e5a..ea9ee7596a0 100644
--- a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{id}/activate_routing_algorithm
+openapi: patch /v2/profiles/{id}/activate-routing-algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
index 87aac8b9379..4d6b2d620c6 100644
--- a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{id}/deactivate_routing_algorithm
+openapi: patch /v2/profiles/{id}/deactivate-routing-algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
index 86d2d35d57c..143837676c2 100644
--- a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{id}/routing_algorithm
+openapi: get /v2/profiles/{id}/routing-algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
index 1bc383c278f..ebaad7c53ae 100644
--- a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{id}/fallback_routing
+openapi: get /v2/profiles/{id}/fallback-routing
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
index 76f4d4fa77f..b5df6a57ef8 100644
--- a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{id}/fallback_routing
+openapi: patch /v2/profiles/{id}/fallback-routing
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/routing/routing--create.mdx b/api-reference-v2/api-reference/routing/routing--create.mdx
index 65ef15008f2..438abd8e231 100644
--- a/api-reference-v2/api-reference/routing/routing--create.mdx
+++ b/api-reference-v2/api-reference/routing/routing--create.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /v2/routing_algorithm
+openapi: post /v2/routing-algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
index 776ff69e004..10db0200e18 100644
--- a/api-reference-v2/api-reference/routing/routing--retrieve.mdx
+++ b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/routing_algorithm/{id}
+openapi: get /v2/routing-algorithm/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index c0723a63f3a..aed89492443 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -23,7 +23,9 @@
"navigation": [
{
"group": "Get Started",
- "pages": ["introduction"]
+ "pages": [
+ "introduction"
+ ]
},
{
"group": "Essentials",
@@ -43,6 +45,19 @@
"api-reference/payments/payments--get"
]
},
+ {
+ "group": "Payment Methods",
+ "pages": [
+ "api-reference/payment-methods/payment-method--create",
+ "api-reference/payment-methods/payment-method--retrieve",
+ "api-reference/payment-methods/payment-method--update",
+ "api-reference/payment-methods/payment-method--delete",
+ "api-reference/payment-methods/payment-method--create-intent",
+ "api-reference/payment-methods/payment-method--confirm-intent",
+ "api-reference/payment-methods/list-customer-saved-payment-methods-for-a-payment",
+ "api-reference/payment-methods/list-payment-methods-for-a-customer"
+ ]
+ },
{
"group": "Organization",
"pages": [
@@ -119,8 +134,10 @@
"github": "https://github.com/juspay/hyperswitch",
"linkedin": "https://www.linkedin.com/company/hyperswitch"
},
- "openapi": ["openapi_spec.json"],
+ "openapi": [
+ "openapi_spec.json"
+ ],
"api": {
"maintainOrder": true
}
-}
+}
\ No newline at end of file
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 1494908c5fc..88ad74a7560 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -164,7 +164,7 @@
]
}
},
- "/v2/organization/{id}/merchant_accounts": {
+ "/v2/organization/{id}/merchant-accounts": {
"get": {
"tags": [
"Organization"
@@ -208,7 +208,7 @@
]
}
},
- "/v2/connector_accounts": {
+ "/v2/connector-accounts": {
"post": {
"tags": [
"Merchant Connector Account"
@@ -285,7 +285,7 @@
]
}
},
- "/v2/connector_accounts/{id}": {
+ "/v2/connector-accounts/{id}": {
"get": {
"tags": [
"Merchant Connector Account"
@@ -445,7 +445,7 @@
]
}
},
- "/v2/merchant_accounts": {
+ "/v2/merchant-accounts": {
"post": {
"tags": [
"Merchant Account"
@@ -524,7 +524,7 @@
]
}
},
- "/v2/merchant_accounts/{id}": {
+ "/v2/merchant-accounts/{id}": {
"get": {
"tags": [
"Merchant Account"
@@ -630,7 +630,7 @@
]
}
},
- "/v2/merchant_accounts/{id}/profiles": {
+ "/v2/merchant-accounts/{id}/profiles": {
"get": {
"tags": [
"Merchant Account"
@@ -907,7 +907,7 @@
]
}
},
- "/v2/profiles/{id}/connector_accounts": {
+ "/v2/profiles/{id}/connector-accounts": {
"get": {
"tags": [
"Business Profile"
@@ -966,7 +966,7 @@
]
}
},
- "/v2/profiles/{id}/activate_routing_algorithm": {
+ "/v2/profiles/{id}/activate-routing-algorithm": {
"patch": {
"tags": [
"Profile"
@@ -1033,7 +1033,7 @@
]
}
},
- "/v2/profiles/{id}/deactivate_routing_algorithm": {
+ "/v2/profiles/{id}/deactivate-routing-algorithm": {
"patch": {
"tags": [
"Profile"
@@ -1086,7 +1086,7 @@
]
}
},
- "/v2/profiles/{id}/fallback_routing": {
+ "/v2/profiles/{id}/fallback-routing": {
"patch": {
"tags": [
"Profile"
@@ -1197,13 +1197,13 @@
]
}
},
- "/v2/profiles/{id}/routing_algorithm": {
+ "/v2/profiles/{id}/routing-algorithm": {
"get": {
"tags": [
"Profile"
],
"summary": "Profile - Retrieve Active Routing Algorithm",
- "description": "Retrieve active routing algorithm under the profile",
+ "description": "_\nRetrieve active routing algorithm under the profile",
"operationId": "Retrieve the active routing algorithm under the profile",
"parameters": [
{
@@ -1271,7 +1271,7 @@
]
}
},
- "/v2/routing_algorithm": {
+ "/v2/routing-algorithm": {
"post": {
"tags": [
"Routing"
@@ -1326,7 +1326,7 @@
]
}
},
- "/v2/routing_algorithm/{id}": {
+ "/v2/routing-algorithm/{id}": {
"get": {
"tags": [
"Routing"
@@ -1376,7 +1376,7 @@
]
}
},
- "/v2/api_keys": {
+ "/v2/api-keys": {
"post": {
"tags": [
"API Key"
@@ -1416,7 +1416,7 @@
]
}
},
- "/v2/api_keys/{id}": {
+ "/v2/api-keys/{id}": {
"get": {
"tags": [
"API Key"
@@ -1545,7 +1545,7 @@
]
}
},
- "/v2/api_keys/list": {
+ "/v2/api-keys/list": {
"get": {
"tags": [
"API Key"
@@ -2017,6 +2017,332 @@
]
}
},
+ "/v2/payments/{id}/saved-payment-methods": {
+ "get": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "List customer saved payment methods for a payment",
+ "description": "To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment",
+ "operationId": "List all Payment Methods for a Customer",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodListRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Methods retrieved for customer tied to its respective client-secret passed in the param",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ },
+ "404": {
+ "description": "Payment Methods does not exist in records"
+ }
+ },
+ "security": [
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
+ "/v2/customers/{id}/saved-payment-methods": {
+ "get": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "List saved payment methods for a Customer",
+ "description": "To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context",
+ "operationId": "List all Payment Methods for a Customer",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodListRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Methods retrieved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomerPaymentMethodsListResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ },
+ "404": {
+ "description": "Payment Methods does not exist in records"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/v2/payment-methods": {
+ "post": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Create",
+ "description": "Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.",
+ "operationId": "Create Payment Method",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodCreate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Method Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/v2/payment-methods/create-intent": {
+ "post": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Create Intent",
+ "description": "Creates a payment method for customer with billing information and other metadata.",
+ "operationId": "Create Payment Method Intent",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodIntentCreate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Method Intent Created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/v2/payment-methods/{id}/confirm-intent": {
+ "post": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Confirm Intent",
+ "description": "Update a payment method with customer's payment method related information.",
+ "operationId": "Confirm Payment Method Intent",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodIntentConfirm"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Method Intent Confirmed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/v2/payment-methods/{id}/update-saved-payment-method": {
+ "patch": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Update",
+ "description": "Update an existing payment method of a customer.",
+ "operationId": "Update Payment Method",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodUpdate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Method Update",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid Data"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/v2/payment-methods/{id}": {
+ "get": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Retrieve",
+ "description": "Retrieves a payment method of a customer.",
+ "operationId": "Retrieve Payment Method",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Method",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method Retrieved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payment Method Not Found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "delete": {
+ "tags": [
+ "Payment Methods"
+ ],
+ "summary": "Payment Method - Delete",
+ "description": "Deletes a payment method of a customer.",
+ "operationId": "Delete Payment Method",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Method",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Method Retrieved",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodDeleteResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payment Method Not Found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/refunds": {
"post": {
"tags": [
@@ -11255,14 +11581,17 @@
],
"properties": {
"organization_name": {
- "type": "string"
+ "type": "string",
+ "description": "Name of the organization"
},
"organization_details": {
"type": "object",
+ "description": "Details about the organization",
"nullable": true
},
"metadata": {
"type": "object",
+ "description": "Metadata is useful for storing additional, unstructured information on an object.",
"nullable": true
}
},
@@ -11271,27 +11600,31 @@
"OrganizationResponse": {
"type": "object",
"required": [
- "organization_id",
+ "id",
"modified_at",
"created_at"
],
"properties": {
- "organization_id": {
+ "id": {
"type": "string",
+ "description": "The unique identifier for the Organization",
"example": "org_q98uSGAYbjEwqs0mJwnz",
"maxLength": 64,
"minLength": 1
},
"organization_name": {
"type": "string",
+ "description": "Name of the Organization",
"nullable": true
},
"organization_details": {
"type": "object",
+ "description": "Details about the organization",
"nullable": true
},
"metadata": {
"type": "object",
+ "description": "Metadata is useful for storing additional, unstructured information on an object.",
"nullable": true
},
"modified_at": {
@@ -11309,14 +11642,17 @@
"properties": {
"organization_name": {
"type": "string",
+ "description": "Name of the organization",
"nullable": true
},
"organization_details": {
"type": "object",
+ "description": "Details about the organization",
"nullable": true
},
"metadata": {
"type": "object",
+ "description": "Metadata is useful for storing additional, unstructured information on an object.",
"nullable": true
}
},
@@ -12906,6 +13242,68 @@
}
}
},
+ "PaymentMethodIntentConfirm": {
+ "type": "object",
+ "required": [
+ "client_secret",
+ "payment_method_data",
+ "payment_method_type",
+ "payment_method_subtype"
+ ],
+ "properties": {
+ "client_secret": {
+ "type": "string",
+ "description": "For SDK based calls, client_secret would be required"
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
+ "nullable": true,
+ "maxLength": 64,
+ "minLength": 1
+ },
+ "payment_method_data": {
+ "$ref": "#/components/schemas/PaymentMethodCreateData"
+ },
+ "payment_method_type": {
+ "$ref": "#/components/schemas/PaymentMethod"
+ },
+ "payment_method_subtype": {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ }
+ },
+ "additionalProperties": false
+ },
+ "PaymentMethodIntentCreate": {
+ "type": "object",
+ "required": [
+ "customer_id"
+ ],
+ "properties": {
+ "metadata": {
+ "type": "object",
+ "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",
+ "nullable": true
+ },
+ "billing": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The unique identifier of the customer.",
+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
+ "maxLength": 64,
+ "minLength": 1
+ }
+ },
+ "additionalProperties": false
+ },
"PaymentMethodIssuerCode": {
"type": "string",
"enum": [
@@ -12947,6 +13345,78 @@
}
]
},
+ "PaymentMethodListRequest": {
+ "type": "object",
+ "properties": {
+ "client_secret": {
+ "type": "string",
+ "description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK",
+ "example": "secret_k2uj3he2893eiu2d",
+ "nullable": true,
+ "maxLength": 30,
+ "minLength": 30
+ },
+ "accepted_countries": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ },
+ "description": "The two-letter ISO currency code",
+ "example": [
+ "US",
+ "UK",
+ "IN"
+ ],
+ "nullable": true
+ },
+ "amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "accepted_currencies": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/Currency"
+ },
+ "description": "The three-letter ISO currency code",
+ "example": [
+ "USD",
+ "EUR"
+ ],
+ "nullable": true
+ },
+ "recurring_enabled": {
+ "type": "boolean",
+ "description": "Indicates whether the payment method is eligible for recurring payments",
+ "example": true,
+ "nullable": true
+ },
+ "card_networks": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CardNetwork"
+ },
+ "description": "Indicates whether the payment method is eligible for card netwotks",
+ "example": [
+ "visa",
+ "mastercard"
+ ],
+ "nullable": true
+ },
+ "limit": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Indicates the limit of last used payment methods",
+ "example": 1,
+ "nullable": true
+ }
+ },
+ "additionalProperties": false
+ },
"PaymentMethodListResponse": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/organization.rs b/crates/api_models/src/organization.rs
index f95a1595116..c6bc3924d11 100644
--- a/crates/api_models/src/organization.rs
+++ b/crates/api_models/src/organization.rs
@@ -22,9 +22,14 @@ pub struct OrganizationId {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct OrganizationCreateRequest {
+ /// Name of the organization
pub organization_name: String,
+
+ /// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
}
@@ -32,20 +37,53 @@ pub struct OrganizationCreateRequest {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct OrganizationUpdateRequest {
+ /// Name of the organization
pub organization_name: Option<String>,
+
+ /// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
}
-
+#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
pub struct OrganizationResponse {
+ /// The unique identifier for the Organization
#[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
pub organization_id: id_type::OrganizationId,
+
+ /// Name of the Organization
pub organization_name: Option<String>,
+
+ /// Details about the organization
#[schema(value_type = Option<Object>)]
pub organization_details: Option<pii::SecretSerdeValue>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
+ #[schema(value_type = Option<Object>)]
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub modified_at: time::PrimitiveDateTime,
+ pub created_at: time::PrimitiveDateTime,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Serialize, Clone, ToSchema)]
+pub struct OrganizationResponse {
+ /// The unique identifier for the Organization
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")]
+ pub id: id_type::OrganizationId,
+
+ /// Name of the Organization
+ pub organization_name: Option<String>,
+
+ /// Details about the organization
+ #[schema(value_type = Option<Object>)]
+ pub organization_details: Option<pii::SecretSerdeValue>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>)]
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: time::PrimitiveDateTime,
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 0bb5e65213f..2c2aa4861c5 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -778,7 +778,7 @@ pub struct PaymentMethodResponse {
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)]
pub struct PaymentMethodResponse {
/// Unique identifier for a merchant
- #[schema(example = "merchant_1671528864", value_type = String)]
+ #[schema(value_type = String, example = "merchant_1671528864")]
pub merchant_id: id_type::MerchantId,
/// The unique identifier of the customer.
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 4cb93403219..6468345b14a 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -123,7 +123,7 @@ impl PaymentIntent {
publishable_key: String,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let start_redirection_url = &format!(
- "{}/v2/payments/{}/start_redirection?publishable_key={}&profile_id={}",
+ "{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}",
base_url,
self.get_id().get_string_repr(),
publishable_key,
@@ -142,7 +142,7 @@ impl PaymentIntent {
publishable_key: &str,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let finish_redirection_url = format!(
- "{base_url}/v2/payments/{}/finish_redirection/{publishable_key}/{}",
+ "{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}",
self.id.get_string_repr(),
self.profile_id.get_string_repr()
);
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 4198e90882e..a756d9fb1b1 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -127,6 +127,17 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
+ //Routes for payment methods
+ routes::payment_method::list_customer_payment_method_for_payment,
+ routes::payment_method::list_customer_payment_method_api,
+ routes::payment_method::create_payment_method_api,
+ routes::payment_method::create_payment_method_intent_api,
+ routes::payment_method::confirm_payment_method_intent_api,
+ routes::payment_method::payment_method_update_api,
+ routes::payment_method::payment_method_retrieve_api,
+ routes::payment_method::payment_method_delete_api,
+
+
//Routes for refunds
routes::refunds::refunds_create,
),
@@ -170,9 +181,12 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::customers::CustomerRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
+ api_models::payment_methods::PaymentMethodIntentCreate,
+ api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethod,
+ api_models::payment_methods::PaymentMethodListRequest,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::ResponsePaymentMethodTypes,
@@ -189,6 +203,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
+ api_models::payment_methods::CardType,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payment_methods::CardType,
api_models::payment_methods::PaymentMethodListData,
diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs
index cfc4c09ce46..964fa60fcf5 100644
--- a/crates/openapi/src/routes/api_keys.rs
+++ b/crates/openapi/src/routes/api_keys.rs
@@ -25,7 +25,7 @@ pub async fn api_key_create() {}
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
- path = "/v2/api_keys",
+ path = "/v2/api-keys",
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
@@ -64,7 +64,7 @@ pub async fn api_key_retrieve() {}
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
- path = "/v2/api_keys/{id}",
+ path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
@@ -106,7 +106,7 @@ pub async fn api_key_update() {}
/// Update information for the specified API Key.
#[utoipa::path(
put,
- path = "/v2/api_keys/{id}",
+ path = "/v2/api-keys/{id}",
request_body = UpdateApiKeyRequest,
params (
("id" = String, Path, description = "The unique identifier for the API Key")
@@ -150,7 +150,7 @@ pub async fn api_key_revoke() {}
/// authenticating with our APIs.
#[utoipa::path(
delete,
- path = "/v2/api_keys/{id}",
+ path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
@@ -191,7 +191,7 @@ pub async fn api_key_list() {}
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
- path = "/v2/api_keys/list",
+ 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."),
diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs
index 022a5e6c006..a3bf96ab897 100644
--- a/crates/openapi/src/routes/merchant_account.rs
+++ b/crates/openapi/src/routes/merchant_account.rs
@@ -50,7 +50,7 @@ pub async fn merchant_account_create() {}
/// Before creating the merchant account, it is mandatory to create an organization.
#[utoipa::path(
post,
- path = "/v2/merchant_accounts",
+ path = "/v2/merchant-accounts",
params(
(
"X-Organization-Id" = String, Header,
@@ -128,7 +128,7 @@ pub async fn retrieve_merchant_account() {}
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
- path = "/v2/merchant_accounts/{id}",
+ path = "/v2/merchant-accounts/{id}",
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
@@ -190,7 +190,7 @@ pub async fn update_merchant_account() {}
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
put,
- path = "/v2/merchant_accounts/{id}",
+ path = "/v2/merchant-accounts/{id}",
request_body (
content = MerchantAccountUpdate,
examples(
@@ -300,7 +300,7 @@ pub async fn payment_connector_list_profile() {}
/// List profiles for an Merchant
#[utoipa::path(
get,
- path = "/v2/merchant_accounts/{id}/profiles",
+ path = "/v2/merchant-accounts/{id}/profiles",
params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs
index 29092b5bba0..372f8688a26 100644
--- a/crates/openapi/src/routes/merchant_connector_account.rs
+++ b/crates/openapi/src/routes/merchant_connector_account.rs
@@ -67,7 +67,7 @@ pub async fn connector_create() {}
#[cfg(feature = "v2")]
#[utoipa::path(
post,
- path = "/v2/connector_accounts",
+ path = "/v2/connector-accounts",
request_body(
content = MerchantConnectorCreate,
examples(
@@ -152,7 +152,7 @@ pub async fn connector_retrieve() {}
#[cfg(feature = "v2")]
#[utoipa::path(
get,
- path = "/v2/connector_accounts/{id}",
+ path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
@@ -241,7 +241,7 @@ pub async fn connector_update() {}
#[cfg(feature = "v2")]
#[utoipa::path(
put,
- path = "/v2/connector_accounts/{id}",
+ path = "/v2/connector-accounts/{id}",
request_body(
content = MerchantConnectorUpdate,
examples(
@@ -310,7 +310,7 @@ pub async fn connector_delete() {}
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
- path = "/v2/connector_accounts/{id}",
+ path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
diff --git a/crates/openapi/src/routes/organization.rs b/crates/openapi/src/routes/organization.rs
index ce3199343cf..d677131d5db 100644
--- a/crates/openapi/src/routes/organization.rs
+++ b/crates/openapi/src/routes/organization.rs
@@ -150,7 +150,7 @@ pub async fn organization_update() {}
/// List merchant accounts for an Organization
#[utoipa::path(
get,
- path = "/v2/organization/{id}/merchant_accounts",
+ path = "/v2/organization/{id}/merchant-accounts",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Merchant Account list retrieved successfully", body = Vec<MerchantAccountResponse>),
diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs
index 3bc593aa5b2..b38a2342678 100644
--- a/crates/openapi/src/routes/payment_method.rs
+++ b/crates/openapi/src/routes/payment_method.rs
@@ -31,6 +31,7 @@
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
+#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
@@ -84,6 +85,7 @@ pub async fn list_payment_method_api() {}
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
+#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
@@ -130,6 +132,7 @@ pub async fn list_customer_payment_method_api_client() {}
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
+#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
@@ -151,6 +154,7 @@ pub async fn payment_method_retrieve_api() {}
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
+#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
@@ -170,6 +174,7 @@ pub async fn payment_method_update_api() {}
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
+#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
@@ -192,3 +197,171 @@ pub async fn payment_method_delete_api() {}
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
+
+/// Payment Method - Create Intent
+///
+/// Creates a payment method for customer with billing information and other metadata.
+#[utoipa::path(
+ post,
+ path = "/v2/payment-methods/create-intent",
+ request_body(
+ content = PaymentMethodIntentCreate,
+ // TODO: Add examples
+ ),
+ responses(
+ (status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
+ (status = 400, description = "Invalid Data"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Create Payment Method Intent",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn create_payment_method_intent_api() {}
+
+/// Payment Method - Confirm Intent
+///
+/// Update a payment method with customer's payment method related information.
+#[utoipa::path(
+ post,
+ path = "/v2/payment-methods/{id}/confirm-intent",
+ request_body(
+ content = PaymentMethodIntentConfirm,
+ // TODO: Add examples
+ ),
+ responses(
+ (status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
+ (status = 400, description = "Invalid Data"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Confirm Payment Method Intent",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn confirm_payment_method_intent_api() {}
+
+/// Payment Method - Create
+///
+/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
+#[utoipa::path(
+ post,
+ path = "/v2/payment-methods",
+ request_body(
+ content = PaymentMethodCreate,
+ // TODO: Add examples
+ ),
+ responses(
+ (status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
+ (status = 400, description = "Invalid Data"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Create Payment Method",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn create_payment_method_api() {}
+
+/// Payment Method - Retrieve
+///
+/// Retrieves a payment method of a customer.
+#[utoipa::path(
+ get,
+ path = "/v2/payment-methods/{id}",
+ params (
+ ("id" = String, Path, description = "The unique identifier for the Payment Method"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
+ (status = 404, description = "Payment Method Not Found"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Retrieve Payment Method",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn payment_method_retrieve_api() {}
+
+/// Payment Method - Update
+///
+/// Update an existing payment method of a customer.
+#[utoipa::path(
+ patch,
+ path = "/v2/payment-methods/{id}/update-saved-payment-method",
+ request_body(
+ content = PaymentMethodUpdate,
+ // TODO: Add examples
+ ),
+ responses(
+ (status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
+ (status = 400, description = "Invalid Data"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Update Payment Method",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn payment_method_update_api() {}
+
+/// Payment Method - Delete
+///
+/// Deletes a payment method of a customer.
+#[utoipa::path(
+ delete,
+ path = "/v2/payment-methods/{id}",
+ params (
+ ("id" = String, Path, description = "The unique identifier for the Payment Method"),
+ ),
+ responses(
+ (status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
+ (status = 404, description = "Payment Method Not Found"),
+ ),
+ tag = "Payment Methods",
+ operation_id = "Delete Payment Method",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn payment_method_delete_api() {}
+
+/// List customer saved payment methods for a payment
+///
+/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment
+#[utoipa::path(
+ get,
+ path = "/v2/payments/{id}/saved-payment-methods",
+ request_body(
+ content = PaymentMethodListRequest,
+ // TODO: Add examples and add param for customer_id
+ ),
+ responses(
+ (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
+ (status = 400, description = "Invalid Data"),
+ (status = 404, description = "Payment Methods does not exist in records")
+ ),
+ tag = "Payment Methods",
+ operation_id = "List all Payment Methods for a Customer",
+ security(("publishable_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn list_customer_payment_method_for_payment() {}
+
+/// List saved payment methods for a Customer
+///
+/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context
+#[utoipa::path(
+ get,
+ path = "/v2/customers/{id}/saved-payment-methods",
+ request_body(
+ content = PaymentMethodListRequest,
+ // TODO: Add examples and add param for customer_id
+ ),
+ responses(
+ (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
+ (status = 400, description = "Invalid Data"),
+ (status = 404, description = "Payment Methods does not exist in records")
+ ),
+ tag = "Payment Methods",
+ operation_id = "List all Payment Methods for a Customer",
+ security(("api_key" = []))
+)]
+#[cfg(feature = "v2")]
+pub async fn list_customer_payment_method_api() {}
diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs
index d88568653a4..cc484aa3f95 100644
--- a/crates/openapi/src/routes/profile.rs
+++ b/crates/openapi/src/routes/profile.rs
@@ -210,7 +210,7 @@ pub async fn profile_update() {}
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{id}/activate_routing_algorithm",
+ path = "/v2/profiles/{id}/activate-routing-algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
@@ -240,7 +240,7 @@ pub async fn routing_link_config() {}
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{id}/deactivate_routing_algorithm",
+ path = "/v2/profiles/{id}/deactivate-routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
@@ -263,7 +263,7 @@ pub async fn routing_unlink_config() {}
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{id}/fallback_routing",
+ path = "/v2/profiles/{id}/fallback-routing",
request_body = Vec<RoutableConnectorChoice>,
params(
("id" = String, Path, description = "The unique identifier for the profile"),
@@ -307,11 +307,11 @@ pub async fn profile_retrieve() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Active Routing Algorithm
-///
+///_
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{id}/routing_algorithm",
+ path = "/v2/profiles/{id}/routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
@@ -334,7 +334,7 @@ pub async fn routing_retrieve_linked_config() {}
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{id}/fallback_routing",
+ path = "/v2/profiles/{id}/fallback-routing",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
@@ -353,7 +353,7 @@ pub async fn routing_retrieve_default_config() {}
/// List Connector Accounts for the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{id}/connector_accounts",
+ path = "/v2/profiles/{id}/connector-accounts",
params(
("id" = String, Path, description = "The unique identifier for the business profile"),
(
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 67a22c2ca64..b144fd046ad 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -26,7 +26,7 @@ pub async fn routing_create_config() {}
/// Create a routing algorithm
#[utoipa::path(
post,
- path = "/v2/routing_algorithm",
+ path = "/v2/routing-algorithm",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
@@ -94,7 +94,7 @@ pub async fn routing_retrieve_config() {}
#[utoipa::path(
get,
- path = "/v2/routing_algorithm/{id}",
+ path = "/v2/routing-algorithm/{id}",
params(
("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1584cfae2b9..96741824254 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -556,11 +556,15 @@ impl Payments {
)
.service(web::resource("").route(web::get().to(payments::payment_status)))
.service(
- web::resource("/start_redirection")
+ web::resource("/start-redirection")
.route(web::get().to(payments::payments_start_redirection)),
)
.service(
- web::resource("/finish_redirection/{publishable_key}/{profile_id}")
+ web::resource("/saved-payment-methods")
+ .route(web::get().to(list_customer_payment_method_for_payment)),
+ )
+ .service(
+ web::resource("/finish-redirection/{publishable_key}/{profile_id}")
.route(web::get().to(payments::payments_finish_redirection)),
),
);
@@ -715,7 +719,7 @@ pub struct Routing;
#[cfg(all(feature = "olap", feature = "v2"))]
impl Routing {
pub fn server(state: AppState) -> Scope {
- web::scope("/v2/routing_algorithm")
+ web::scope("/v2/routing-algorithm")
.app_data(web::Data::new(state.clone()))
.service(
web::resource("").route(web::post().to(|state, req, payload| {
@@ -968,7 +972,7 @@ impl Customers {
#[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))]
{
route = route.service(
- web::resource("/{customer_id}/saved_payment_methods")
+ web::resource("/{customer_id}/saved-payment-methods")
.route(web::get().to(list_customer_payment_method_api)),
);
}
@@ -1113,7 +1117,7 @@ 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));
+ 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(
@@ -1125,7 +1129,7 @@ impl PaymentMethods {
.route(web::post().to(confirm_payment_method_intent_api)),
)
.service(
- web::resource("/{id}/update_saved_payment_method")
+ 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)))
@@ -1267,7 +1271,7 @@ impl Organization {
.route(web::put().to(admin::organization_update)),
)
.service(
- web::resource("/merchant_accounts")
+ web::resource("/merchant-accounts")
.route(web::get().to(admin::merchant_account_list)),
),
)
@@ -1279,7 +1283,7 @@ pub struct MerchantAccount;
#[cfg(all(feature = "v2", feature = "olap"))]
impl MerchantAccount {
pub fn server(state: AppState) -> Scope {
- web::scope("/v2/merchant_accounts")
+ web::scope("/v2/merchant-accounts")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(admin::merchant_account_create)))
.service(
@@ -1329,7 +1333,7 @@ pub struct MerchantConnectorAccount;
#[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v2"))]
impl MerchantConnectorAccount {
pub fn server(state: AppState) -> Scope {
- let mut route = web::scope("/v2/connector_accounts").app_data(web::Data::new(state));
+ let mut route = web::scope("/v2/connector-accounts").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
@@ -1526,7 +1530,7 @@ pub struct ApiKeys;
#[cfg(all(feature = "olap", feature = "v2"))]
impl ApiKeys {
pub fn server(state: AppState) -> Scope {
- web::scope("/v2/api_keys")
+ web::scope("/v2/api-keys")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(api_keys::api_key_create)))
.service(web::resource("/list").route(web::get().to(api_keys::api_key_list)))
@@ -1692,16 +1696,16 @@ impl Profile {
.route(web::put().to(profiles::profile_update)),
)
.service(
- web::resource("/connector_accounts")
+ web::resource("/connector-accounts")
.route(web::get().to(admin::connector_list)),
)
.service(
- web::resource("/fallback_routing")
+ web::resource("/fallback-routing")
.route(web::get().to(routing::routing_retrieve_default_config))
.route(web::patch().to(routing::routing_update_default_config)),
)
.service(
- web::resource("/activate_routing_algorithm").route(web::patch().to(
+ web::resource("/activate-routing-algorithm").route(web::patch().to(
|state, req, path, payload| {
routing::routing_link_config(
state,
@@ -1714,7 +1718,7 @@ impl Profile {
)),
)
.service(
- web::resource("/deactivate_routing_algorithm").route(web::patch().to(
+ web::resource("/deactivate-routing-algorithm").route(web::patch().to(
|state, req, path| {
routing::routing_unlink_config(
state,
@@ -1725,7 +1729,7 @@ impl Profile {
},
)),
)
- .service(web::resource("/routing_algorithm").route(web::get().to(
+ .service(web::resource("/routing-algorithm").route(web::get().to(
|state, req, query_params, path| {
routing::routing_retrieve_linked_config(
state,
@@ -2000,7 +2004,7 @@ impl User {
)
.service(web::resource("/verify_email").route(web::post().to(user::verify_email)))
.service(
- web::resource("/v2/verify_email").route(web::post().to(user::verify_email)),
+ web::resource("/v2/verify-email").route(web::post().to(user::verify_email)),
)
.service(
web::resource("/verify_email_request")
@@ -2054,7 +2058,7 @@ impl User {
.route(web::post().to(user_role::accept_invitations_v2)),
)
.service(
- web::resource("/pre_auth").route(
+ web::resource("/pre-auth").route(
web::post().to(user_role::accept_invitations_pre_auth),
),
),
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 7296a510248..8ee31ecf943 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -508,30 +508,6 @@ pub async fn list_customer_payment_method_api(
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-/// List payment methods for a Customer v2
-///
-/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment
-#[utoipa::path(
- get,
- path = "v2/payments/{payment_id}/saved_payment_methods",
- params (
- ("client-secret" = String, Path, description = "A secret known only to your application and the authorization server"),
- ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
- ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
- ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
- ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
- ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
- ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
- ),
- responses(
- (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
- (status = 400, description = "Invalid Data"),
- (status = 404, description = "Payment Methods does not exist in records")
- ),
- tag = "Payment Methods",
- operation_id = "List all Payment Methods for a Customer",
- security(("publishable_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_for_payment(
state: web::Data<AppState>,
@@ -575,29 +551,6 @@ pub async fn list_customer_payment_method_for_payment(
feature = "payment_methods_v2",
feature = "customer_v2"
))]
-/// List payment methods for a Customer v2
-///
-/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context
-#[utoipa::path(
- get,
- path = "v2/customers/{customer_id}/saved_payment_methods",
- params (
- ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
- ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
- ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
- ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
- ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
- ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
- ),
- responses(
- (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
- (status = 400, description = "Invalid Data"),
- (status = 404, description = "Payment Methods does not exist in records")
- ),
- tag = "Payment Methods",
- operation_id = "List all Payment Methods for a Customer",
- security(("api_key" = []))
-)]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<AppState>,
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index c81fc7ceb48..85275a768df 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -34,6 +34,10 @@ use crate::{
impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse {
fn foreign_from(org: diesel_models::organization::Organization) -> Self {
Self {
+ #[cfg(feature = "v2")]
+ id: org.get_organization_id(),
+
+ #[cfg(feature = "v1")]
organization_id: org.get_organization_id(),
organization_name: org.get_organization_name(),
organization_details: org.organization_details,
diff --git a/cypress-tests-v2/cypress/support/commands.js b/cypress-tests-v2/cypress/support/commands.js
index eb4ca3423eb..b6955c542a7 100644
--- a/cypress-tests-v2/cypress/support/commands.js
+++ b/cypress-tests-v2/cypress/support/commands.js
@@ -64,10 +64,10 @@ Cypress.Commands.add(
if (response.status === 200) {
expect(response.body)
- .to.have.property("organization_id")
+ .to.have.property("id")
.and.to.include("org_")
.and.to.be.a("string").and.not.be.empty;
- globalState.set("organizationId", response.body.organization_id);
+ globalState.set("organizationId", response.body.id);
cy.task("setGlobalState", globalState.data);
expect(response.body).to.have.property("metadata").and.to.equal(null);
} else {
@@ -99,7 +99,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => {
if (response.status === 200) {
expect(response.body)
- .to.have.property("organization_id")
+ .to.have.property("id")
.and.to.include("org_")
.and.to.be.a("string").and.not.be.empty;
expect(response.body.organization_name)
@@ -107,7 +107,7 @@ Cypress.Commands.add("organizationRetrieveCall", (globalState) => {
.and.to.be.a("string").and.not.be.empty;
if (organization_id === undefined || organization_id === null) {
- globalState.set("organizationId", response.body.organization_id);
+ globalState.set("organizationId", response.body.id);
cy.task("setGlobalState", globalState.data);
}
} else {
@@ -144,14 +144,14 @@ Cypress.Commands.add(
if (response.status === 200) {
expect(response.body)
- .to.have.property("organization_id")
+ .to.have.property("id")
.and.to.include("org_")
.and.to.be.a("string").and.not.be.empty;
expect(response.body).to.have.property("metadata").and.to.be.a("object")
.and.not.be.empty;
if (organization_id === undefined || organization_id === null) {
- globalState.set("organizationId", response.body.organization_id);
+ globalState.set("organizationId", response.body.id);
cy.task("setGlobalState", globalState.data);
}
} else {
@@ -174,7 +174,7 @@ Cypress.Commands.add(
const key_id_type = "publishable_key";
const key_id = validateEnv(base_url, key_id_type);
const organization_id = globalState.get("organizationId");
- const url = `${base_url}/v2/merchant_accounts`;
+ const url = `${base_url}/v2/merchant-accounts`;
const merchant_name = merchantAccountCreateBody.merchant_name
.replaceAll(" ", "")
@@ -223,7 +223,7 @@ Cypress.Commands.add("merchantAccountRetrieveCall", (globalState) => {
const key_id_type = "publishable_key";
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/merchant_accounts/${merchant_id}`;
+ const url = `${base_url}/v2/merchant-accounts/${merchant_id}`;
cy.request({
method: "GET",
@@ -265,7 +265,7 @@ Cypress.Commands.add(
const key_id_type = "publishable_key";
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/merchant_accounts/${merchant_id}`;
+ const url = `${base_url}/v2/merchant-accounts/${merchant_id}`;
const merchant_name = merchantAccountUpdateBody.merchant_name;
@@ -456,7 +456,7 @@ Cypress.Commands.add(
const base_url = globalState.get("baseUrl");
const merchant_id = globalState.get("merchantId");
const profile_id = globalState.get("profileId");
- const url = `${base_url}/v2/connector_accounts`;
+ const url = `${base_url}/v2/connector-accounts`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -536,7 +536,7 @@ Cypress.Commands.add("mcaRetrieveCall", (globalState) => {
const connector_name = globalState.get("connectorId");
const merchant_connector_id = globalState.get("merchantConnectorId");
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/connector_accounts/${merchant_connector_id}`;
+ const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -590,7 +590,7 @@ Cypress.Commands.add(
const merchant_connector_id = globalState.get("merchantConnectorId");
const merchant_id = globalState.get("merchantId");
const profile_id = globalState.get("profileId");
- const url = `${base_url}/v2/connector_accounts/${merchant_connector_id}`;
+ const url = `${base_url}/v2/connector-accounts/${merchant_connector_id}`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -653,7 +653,7 @@ Cypress.Commands.add("apiKeyCreateCall", (apiKeyCreateBody, globalState) => {
const key_id_type = "key_id";
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/api_keys`;
+ const url = `${base_url}/v2/api-keys`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -703,7 +703,7 @@ Cypress.Commands.add("apiKeyRetrieveCall", (globalState) => {
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
const api_key_id = globalState.get("apiKeyId");
- const url = `${base_url}/v2/api_keys/${api_key_id}`;
+ const url = `${base_url}/v2/api-keys/${api_key_id}`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -750,7 +750,7 @@ Cypress.Commands.add("apiKeyUpdateCall", (apiKeyUpdateBody, globalState) => {
const key_id_type = "key_id";
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/api_keys/${api_key_id}`;
+ const url = `${base_url}/v2/api-keys/${api_key_id}`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -801,7 +801,7 @@ Cypress.Commands.add(
const api_key = globalState.get("userInfoToken");
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
- const url = `${base_url}/v2/routing_algorithm`;
+ const url = `${base_url}/v2/routing-algorithm`;
// Update request body
routingSetupBody.algorithm.data = payload.data;
@@ -847,7 +847,7 @@ Cypress.Commands.add(
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
const routing_algorithm_id = globalState.get("routingAlgorithmId");
- const url = `${base_url}/v2/profiles/${profile_id}/activate_routing_algorithm`;
+ const url = `${base_url}/v2/profiles/${profile_id}/activate-routing-algorithm`;
// Update request body
routingActivationBody.routing_algorithm_id = routing_algorithm_id;
@@ -885,7 +885,7 @@ Cypress.Commands.add("routingActivationRetrieveCall", (globalState) => {
const profile_id = globalState.get("profileId");
const query_params = "limit=10";
const routing_algorithm_id = globalState.get("routingAlgorithmId");
- const url = `${base_url}/v2/profiles/${profile_id}/routing_algorithm?${query_params}`;
+ const url = `${base_url}/v2/profiles/${profile_id}/routing-algorithm?${query_params}`;
cy.request({
method: "GET",
@@ -922,7 +922,7 @@ Cypress.Commands.add("routingDeactivateCall", (globalState) => {
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
const routing_algorithm_id = globalState.get("routingAlgorithmId");
- const url = `${base_url}/v2/profiles/${profile_id}/deactivate_routing_algorithm`;
+ const url = `${base_url}/v2/profiles/${profile_id}/deactivate-routing-algorithm`;
cy.request({
method: "PATCH",
@@ -957,7 +957,7 @@ Cypress.Commands.add("routingRetrieveCall", (globalState) => {
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
const routing_algorithm_id = globalState.get("routingAlgorithmId");
- const url = `${base_url}/v2/routing_algorithm/${routing_algorithm_id}`;
+ const url = `${base_url}/v2/routing-algorithm/${routing_algorithm_id}`;
cy.request({
method: "GET",
@@ -996,7 +996,7 @@ Cypress.Commands.add(
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
const routing_algorithm_id = globalState.get("routingAlgorithmId");
- const url = `${base_url}/v2/profiles/${profile_id}/fallback_routing`;
+ const url = `${base_url}/v2/profiles/${profile_id}/fallback-routing`;
// Update request body
routingDefaultFallbackBody = payload;
@@ -1029,7 +1029,7 @@ Cypress.Commands.add("routingFallbackRetrieveCall", (globalState) => {
const api_key = globalState.get("userInfoToken");
const base_url = globalState.get("baseUrl");
const profile_id = globalState.get("profileId");
- const url = `${base_url}/v2/profiles/${profile_id}/fallback_routing`;
+ const url = `${base_url}/v2/profiles/${profile_id}/fallback-routing`;
cy.request({
method: "GET",
@@ -1166,7 +1166,7 @@ Cypress.Commands.add("merchantAccountsListCall", (globalState) => {
const key_id_type = "publishable_key";
const key_id = validateEnv(base_url, key_id_type);
const organization_id = globalState.get("organizationId");
- const url = `${base_url}/v2/organization/${organization_id}/merchant_accounts`;
+ const url = `${base_url}/v2/organization/${organization_id}/merchant-accounts`;
cy.request({
method: "GET",
@@ -1204,7 +1204,7 @@ Cypress.Commands.add("businessProfilesListCall", (globalState) => {
const api_key = globalState.get("adminApiKey");
const base_url = globalState.get("baseUrl");
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/merchant_accounts/${merchant_id}/profiles`;
+ const url = `${base_url}/v2/merchant-accounts/${merchant_id}/profiles`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -1246,7 +1246,7 @@ Cypress.Commands.add("mcaListCall", (globalState, service_type) => {
const base_url = globalState.get("baseUrl");
const merchant_id = globalState.get("merchantId");
const profile_id = globalState.get("profileId");
- const url = `${base_url}/v2/profiles/${profile_id}/connector_accounts`;
+ const url = `${base_url}/v2/profiles/${profile_id}/connector-accounts`;
const customHeaders = {
"x-merchant-id": merchant_id,
@@ -1308,7 +1308,7 @@ Cypress.Commands.add("apiKeysListCall", (globalState) => {
const key_id_type = "key_id";
const key_id = validateEnv(base_url, key_id_type);
const merchant_id = globalState.get("merchantId");
- const url = `${base_url}/v2/api_keys/list`;
+ const url = `${base_url}/v2/api-keys/list`;
const customHeaders = {
"x-merchant-id": merchant_id,
|
2024-11-07T13:12:55Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Use kebab-case for all API endpoints in V2
### 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)?
-->
This is mostly a documentation PR, doesn't require any additional test cases.
Verified that existing cypress tests are passing
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6495
|
Bug: [DOCS] FIx API documentation for V2
- Merchant Account Update: Path Parameters in definition says it is {account_id} instead that should be {id}
- Merchant Profile List Changes: Instead `Profile - list` make `Merchant Account - Profile List` , Path Parameters in definition says it is {account_id} instead that should be {id}
- Profile Changes: In profile all routes has [profile_id] in the path, change the path to [id] and the explanation in path parameter also to [id]. For `Merchant Connector - list` in side-bar, change to `Profile - Connector Accounts list`. In the definition of the api
`List Merchant Connector Details for the business profile` instead
`List Connector Accounts for the profile`
- Connector Account Changes: Instead of `Merchant Connector Account` use the term `Connector Account`
- Api-Key Changes: In the path param and its definition we are using {key_id] instead use [id]
- Routing Changes: In path param and its definition we are using {routing_algorithm_id} instead is {id] , these changes are in api-documentation
|
diff --git a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
index 13b87953f1b..ee7970122d4 100644
--- a/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/api_keys/{key_id}
+openapi: get /v2/api_keys/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
index 37a9c9fcc09..9362743088b 100644
--- a/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--revoke.mdx
@@ -1,3 +1,3 @@
---
-openapi: delete /v2/api_keys/{key_id}
+openapi: delete /v2/api_keys/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/api-key/api-key--update.mdx b/api-reference-v2/api-reference/api-key/api-key--update.mdx
index 8d1b6e2ee11..c682cf1ee9e 100644
--- a/api-reference-v2/api-reference/api-key/api-key--update.mdx
+++ b/api-reference-v2/api-reference/api-key/api-key--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: put /v2/api_keys/{key_id}
+openapi: put /v2/api_keys/{id}
---
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx b/api-reference-v2/api-reference/connector-account/connector-account--create.mdx
similarity index 100%
rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--create.mdx
rename to api-reference-v2/api-reference/connector-account/connector-account--create.mdx
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx b/api-reference-v2/api-reference/connector-account/connector-account--delete.mdx
similarity index 100%
rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--delete.mdx
rename to api-reference-v2/api-reference/connector-account/connector-account--delete.mdx
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx b/api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx
similarity index 100%
rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--retrieve.mdx
rename to api-reference-v2/api-reference/connector-account/connector-account--retrieve.mdx
diff --git a/api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx b/api-reference-v2/api-reference/connector-account/connector-account--update.mdx
similarity index 100%
rename from api-reference-v2/api-reference/merchant-connector-account/merchant-connector--update.mdx
rename to api-reference-v2/api-reference/connector-account/connector-account--update.mdx
diff --git a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
index e14bc0d6ef3..97deb0832cc 100644
--- a/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
+++ b/api-reference-v2/api-reference/merchant-account/business-profile--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/merchant_accounts/{account_id}/profiles
+openapi: get /v2/merchant_accounts/{id}/profiles
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/payments/payments--session-token.mdx b/api-reference-v2/api-reference/payments/payments--session-token.mdx
index 2b4f6b0bec6..615bafcc03d 100644
--- a/api-reference-v2/api-reference/payments/payments--session-token.mdx
+++ b/api-reference-v2/api-reference/payments/payments--session-token.mdx
@@ -1,3 +1,3 @@
---
-openapi: post /v2/payments/{payment_id}/create_external_sdk_tokens
+openapi: post /v2/payments/{payment_id}/create-external-sdk-tokens
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
index 6560f45e5fa..81f640436f4 100644
--- a/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
+++ b/api-reference-v2/api-reference/profile/merchant-connector--list.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{profile_id}/connector_accounts
+openapi: get /v2/profiles/{id}/connector_accounts
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
index 9ff6f4fdd57..7225f422e5a 100644
--- a/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--activate-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{profile_id}/activate_routing_algorithm
+openapi: patch /v2/profiles/{id}/activate_routing_algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
index 5cc815612e0..87aac8b9379 100644
--- a/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--deactivate-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{profile_id}/deactivate_routing_algorithm
+openapi: patch /v2/profiles/{id}/deactivate_routing_algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
index 7aba27485ed..86d2d35d57c 100644
--- a/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--retrieve-active-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{profile_id}/routing_algorithm
+openapi: get /v2/profiles/{id}/routing_algorithm
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
index 9b1b9429077..1bc383c278f 100644
--- a/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--retrieve-default-fallback-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{profile_id}/fallback_routing
+openapi: get /v2/profiles/{id}/fallback_routing
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--retrieve.mdx b/api-reference-v2/api-reference/profile/profile--retrieve.mdx
index 235bb7d7f50..28ca1fbd1b1 100644
--- a/api-reference-v2/api-reference/profile/profile--retrieve.mdx
+++ b/api-reference-v2/api-reference/profile/profile--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/profiles/{profile_id}
+openapi: get /v2/profiles/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
index 0ba69796a7e..76f4d4fa77f 100644
--- a/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
+++ b/api-reference-v2/api-reference/profile/profile--update-default-fallback-routing-algorithm.mdx
@@ -1,3 +1,3 @@
---
-openapi: patch /v2/profiles/{profile_id}/fallback_routing
+openapi: patch /v2/profiles/{id}/fallback_routing
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/profile/profile--update.mdx b/api-reference-v2/api-reference/profile/profile--update.mdx
index bf35d0afb64..21b50001c63 100644
--- a/api-reference-v2/api-reference/profile/profile--update.mdx
+++ b/api-reference-v2/api-reference/profile/profile--update.mdx
@@ -1,3 +1,3 @@
---
-openapi: put /v2/profiles/{profile_id}
+openapi: put /v2/profiles/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/api-reference/routing/routing--retrieve.mdx b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
index 03f209951c0..776ff69e004 100644
--- a/api-reference-v2/api-reference/routing/routing--retrieve.mdx
+++ b/api-reference-v2/api-reference/routing/routing--retrieve.mdx
@@ -1,3 +1,3 @@
---
-openapi: get /v2/routing_algorithm/{routing_algorithm_id}
+openapi: get /v2/routing_algorithm/{id}
---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index 17dd6dfb7ff..dc47cf5d4c0 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -76,11 +76,11 @@
]
},
{
- "group": "Merchant Connector Account",
+ "group": "Connector Account",
"pages": [
- "api-reference/merchant-connector-account/merchant-connector--create",
- "api-reference/merchant-connector-account/merchant-connector--retrieve",
- "api-reference/merchant-connector-account/merchant-connector--update"
+ "api-reference/connector-account/connector-account--create",
+ "api-reference/connector-account/connector-account--retrieve",
+ "api-reference/connector-account/connector-account--update"
]
},
{
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 4c1559fe099..1f955ab1d80 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -213,8 +213,8 @@
"tags": [
"Merchant Connector Account"
],
- "summary": "Merchant Connector - Create",
- "description": "Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.",
+ "summary": "Connector Account - Create",
+ "description": "Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.",
"operationId": "Create a Merchant Connector",
"requestBody": {
"content": {
@@ -290,7 +290,7 @@
"tags": [
"Merchant Connector Account"
],
- "summary": "Merchant Connector - Retrieve",
+ "summary": "Connector Account - Retrieve",
"description": "Retrieves details of a Connector account",
"operationId": "Retrieve a Merchant Connector",
"parameters": [
@@ -333,8 +333,8 @@
"tags": [
"Merchant Connector Account"
],
- "summary": "Merchant Connector - Update",
- "description": "To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector",
+ "summary": "Connector Account - Update",
+ "description": "To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector",
"operationId": "Update a Merchant Connector",
"parameters": [
{
@@ -573,7 +573,7 @@
"operationId": "Update a Merchant Account",
"parameters": [
{
- "name": "account_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the merchant account",
"required": true,
@@ -630,17 +630,17 @@
]
}
},
- "/v2/merchant_accounts/{account_id}/profiles": {
+ "/v2/merchant_accounts/{id}/profiles": {
"get": {
"tags": [
"Merchant Account"
],
- "summary": "Profile - List",
+ "summary": "Merchant Account - Profile List",
"description": "List profiles for an Merchant",
"operationId": "List Profiles",
"parameters": [
{
- "name": "account_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the Merchant",
"required": true,
@@ -682,6 +682,17 @@
"summary": "Payments - Session token",
"description": "Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.",
"operationId": "Create Session tokens for a Payment",
+ "parameters": [
+ {
+ "name": "payment_id",
+ "in": "path",
+ "description": "The identifier for payment",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -775,7 +786,7 @@
]
}
},
- "/v2/profiles/{profile_id}": {
+ "/v2/profiles/{id}": {
"get": {
"tags": [
"Profile"
@@ -785,7 +796,7 @@
"operationId": "Retrieve a Profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -836,7 +847,7 @@
"operationId": "Update a Profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -896,17 +907,17 @@
]
}
},
- "/v2/profiles/{profile_id}/connector_accounts": {
+ "/v2/profiles/{id}/connector_accounts": {
"get": {
"tags": [
"Business Profile"
],
- "summary": "Merchant Connector - List",
- "description": "List Merchant Connector Details for the business profile",
+ "summary": "Profile - Connector Accounts List",
+ "description": "List Connector Accounts for the profile",
"operationId": "List all Merchant Connectors",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the business profile",
"required": true,
@@ -955,7 +966,7 @@
]
}
},
- "/v2/profiles/{profile_id}/activate_routing_algorithm": {
+ "/v2/profiles/{id}/activate_routing_algorithm": {
"patch": {
"tags": [
"Profile"
@@ -965,7 +976,7 @@
"operationId": "Activates a routing algorithm under a profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -1022,7 +1033,7 @@
]
}
},
- "/v2/profiles/{profile_id}/deactivate_routing_algorithm": {
+ "/v2/profiles/{id}/deactivate_routing_algorithm": {
"patch": {
"tags": [
"Profile"
@@ -1032,7 +1043,7 @@
"operationId": " Deactivates a routing algorithm under a profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -1075,7 +1086,7 @@
]
}
},
- "/v2/profiles/{profile_id}/fallback_routing": {
+ "/v2/profiles/{id}/fallback_routing": {
"patch": {
"tags": [
"Profile"
@@ -1085,7 +1096,7 @@
"operationId": "Update the default fallback routing algorithm for the profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -1149,7 +1160,7 @@
"operationId": "Retrieve the default fallback routing algorithm for the profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -1186,7 +1197,7 @@
]
}
},
- "/v2/profiles/{profile_id}/routing_algorithm": {
+ "/v2/profiles/{id}/routing_algorithm": {
"get": {
"tags": [
"Profile"
@@ -1196,7 +1207,7 @@
"operationId": "Retrieve the active routing algorithm under the profile",
"parameters": [
{
- "name": "profile_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the profile",
"required": true,
@@ -1315,7 +1326,7 @@
]
}
},
- "/v2/routing_algorithm/{routing_algorithm_id}": {
+ "/v2/routing_algorithm/{id}": {
"get": {
"tags": [
"Routing"
@@ -1325,7 +1336,7 @@
"operationId": "Retrieve a routing algorithm with its algorithm id",
"parameters": [
{
- "name": "routing_algorithm_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for a routing algorithm",
"required": true,
@@ -1405,7 +1416,7 @@
]
}
},
- "/v2/api_keys/{key_id}": {
+ "/v2/api_keys/{id}": {
"get": {
"tags": [
"API Key"
@@ -1415,7 +1426,7 @@
"operationId": "Retrieve an API Key",
"parameters": [
{
- "name": "key_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the API Key",
"required": true,
@@ -1454,7 +1465,7 @@
"operationId": "Update an API Key",
"parameters": [
{
- "name": "key_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the API Key",
"required": true,
@@ -1503,7 +1514,7 @@
"operationId": "Revoke an API Key",
"parameters": [
{
- "name": "key_id",
+ "name": "id",
"in": "path",
"description": "The unique identifier for the API Key",
"required": true,
@@ -20082,7 +20093,7 @@
"type": "apiKey",
"in": "header",
"name": "api-key",
- "description": "Admin API keys allow you to perform some privileged actions such as creating a merchant account and Merchant Connector account."
+ "description": "Admin API keys allow you to perform some privileged actions such as creating a merchant account and Connector account."
},
"api_key": {
"type": "apiKey",
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 40f694b80a2..13706912ecd 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -614,7 +614,7 @@ impl utoipa::Modify for SecurityAddon {
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
- creating a merchant account and Merchant Connector account."
+ creating a merchant account and Connector account."
))),
),
(
diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs
index 7527c8a1095..cfc4c09ce46 100644
--- a/crates/openapi/src/routes/api_keys.rs
+++ b/crates/openapi/src/routes/api_keys.rs
@@ -64,9 +64,9 @@ pub async fn api_key_retrieve() {}
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
- path = "/v2/api_keys/{key_id}",
+ path = "/v2/api_keys/{id}",
params (
- ("key_id" = String, Path, description = "The unique identifier for the API Key")
+ ("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
@@ -106,10 +106,10 @@ pub async fn api_key_update() {}
/// Update information for the specified API Key.
#[utoipa::path(
put,
- path = "/v2/api_keys/{key_id}",
+ path = "/v2/api_keys/{id}",
request_body = UpdateApiKeyRequest,
params (
- ("key_id" = String, Path, description = "The unique identifier for the API Key")
+ ("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
@@ -150,9 +150,9 @@ pub async fn api_key_revoke() {}
/// authenticating with our APIs.
#[utoipa::path(
delete,
- path = "/v2/api_keys/{key_id}",
+ path = "/v2/api_keys/{id}",
params (
- ("key_id" = String, Path, description = "The unique identifier for the API Key")
+ ("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs
index 01571da1de9..022a5e6c006 100644
--- a/crates/openapi/src/routes/merchant_account.rs
+++ b/crates/openapi/src/routes/merchant_account.rs
@@ -212,7 +212,7 @@ pub async fn update_merchant_account() {}
)
),
)),
- params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
+ params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
@@ -295,13 +295,13 @@ pub async fn merchant_account_kv_status() {}
pub async fn payment_connector_list_profile() {}
#[cfg(feature = "v2")]
-/// Profile - List
+/// Merchant Account - Profile List
///
/// List profiles for an Merchant
#[utoipa::path(
get,
- path = "/v2/merchant_accounts/{account_id}/profiles",
- params (("account_id" = String, Path, description = "The unique identifier for the Merchant")),
+ path = "/v2/merchant_accounts/{id}/profiles",
+ params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
(status = 400, description = "Invalid data")
diff --git a/crates/openapi/src/routes/merchant_connector_account.rs b/crates/openapi/src/routes/merchant_connector_account.rs
index a9cabde8af4..29092b5bba0 100644
--- a/crates/openapi/src/routes/merchant_connector_account.rs
+++ b/crates/openapi/src/routes/merchant_connector_account.rs
@@ -61,9 +61,9 @@
)]
pub async fn connector_create() {}
-/// Merchant Connector - Create
+/// Connector Account - Create
///
-/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
+/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v2")]
#[utoipa::path(
post,
@@ -146,7 +146,7 @@ pub async fn connector_create() {}
)]
pub async fn connector_retrieve() {}
-/// Merchant Connector - Retrieve
+/// Connector Account - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v2")]
@@ -235,9 +235,9 @@ pub async fn connector_list() {}
)]
pub async fn connector_update() {}
-/// Merchant Connector - Update
+/// Connector Account - Update
///
-/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
+/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v2")]
#[utoipa::path(
put,
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index e245c5af68a..77e5bea10f3 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -406,6 +406,9 @@ pub fn payments_connector_session() {}
#[utoipa::path(
post,
path = "/v2/payments/{payment_id}/create-external-sdk-tokens",
+ params(
+ ("payment_id" = String, Path, description = "The identifier for payment")
+ ),
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
diff --git a/crates/openapi/src/routes/profile.rs b/crates/openapi/src/routes/profile.rs
index fc56e642719..d88568653a4 100644
--- a/crates/openapi/src/routes/profile.rs
+++ b/crates/openapi/src/routes/profile.rs
@@ -174,9 +174,9 @@ pub async fn profile_create() {}
/// Update the *profile*
#[utoipa::path(
put,
- path = "/v2/profiles/{profile_id}",
+ path = "/v2/profiles/{id}",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
@@ -210,7 +210,7 @@ pub async fn profile_update() {}
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{profile_id}/activate_routing_algorithm",
+ path = "/v2/profiles/{id}/activate_routing_algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
@@ -220,7 +220,7 @@ pub async fn profile_update() {}
)
))),
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
@@ -240,9 +240,9 @@ pub async fn routing_link_config() {}
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{profile_id}/deactivate_routing_algorithm",
+ path = "/v2/profiles/{id}/deactivate_routing_algorithm",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
@@ -263,10 +263,10 @@ pub async fn routing_unlink_config() {}
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
- path = "/v2/profiles/{profile_id}/fallback_routing",
+ path = "/v2/profiles/{id}/fallback_routing",
request_body = Vec<RoutableConnectorChoice>,
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
@@ -286,9 +286,9 @@ pub async fn routing_update_default_config() {}
/// Retrieve existing *profile*
#[utoipa::path(
get,
- path = "/v2/profiles/{profile_id}",
+ path = "/v2/profiles/{id}",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
@@ -311,9 +311,9 @@ pub async fn profile_retrieve() {}
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{profile_id}/routing_algorithm",
+ path = "/v2/profiles/{id}/routing_algorithm",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
responses(
@@ -334,9 +334,9 @@ pub async fn routing_retrieve_linked_config() {}
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{profile_id}/fallback_routing",
+ path = "/v2/profiles/{id}/fallback_routing",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the profile"),
+ ("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
@@ -348,14 +348,14 @@ pub async fn routing_retrieve_linked_config() {}
)]
pub async fn routing_retrieve_default_config() {}
-/// Merchant Connector - List
+/// Profile - Connector Accounts List
///
-/// List Merchant Connector Details for the business profile
+/// List Connector Accounts for the profile
#[utoipa::path(
get,
- path = "/v2/profiles/{profile_id}/connector_accounts",
+ path = "/v2/profiles/{id}/connector_accounts",
params(
- ("profile_id" = String, Path, description = "The unique identifier for the business profile"),
+ ("id" = String, Path, description = "The unique identifier for the business profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 0bb79a2bbe4..67a22c2ca64 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -94,9 +94,9 @@ pub async fn routing_retrieve_config() {}
#[utoipa::path(
get,
- path = "/v2/routing_algorithm/{routing_algorithm_id}",
+ path = "/v2/routing_algorithm/{id}",
params(
- ("routing_algorithm_id" = String, Path, description = "The unique identifier for a routing algorithm"),
+ ("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
responses(
(status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
|
2024-11-06T13:16:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Improved OpenAPI documentation 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`
-->
## Issues Addressed
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Merchant Account Update: Path Parameters in definition says it is {account_id} instead that should be {id}
- Merchant Profile List Changes: Instead `Profile - list` make `Merchant Account - Profile List` , Path Parameters in definition says it is {account_id} instead that should be {id}
- Profile Changes: In profile all routes has [profile_id] in the path, change the path to [id] and the explanation in path parameter also to [id]. For `Merchant Connector - list` in side-bar, change to `Profile - Connector Accounts list`. In the definition of the api
`List Merchant Connector Details for the business profile` instead
`List Connector Accounts for the profile`
- Connector Account Changes: Instead of `Merchant Connector Account` use the term `Connector Account`
- Api-Key Changes: In the path param and its definition we are using {key_id] instead use [id]
- Routing Changes: In path param and its definition we are using {routing_algorithm_id} instead is {id] , these changes are in api-documentation
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
01c5216fdd6f1d841082868cccea6054b64e9e07
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6524
|
Bug: [FEATURE] add permissions for operations in recon module
### Feature Description
Reconciliation module in HyperSwitch provides various operations. Every operation needs to permitted for the end user to use it.
As of today, recon has a single permission - which gives access to the entire recon module, this is not granular. Recon module's permission suite needs to be extended to be able to assign granular access for different operations.
### Possible Implementation
Add permissions for below operations
- Upload files - RW
- Run recon - RW
- View and update recon configs - RW
- View and add file processing - RW
- View Reports - R
- View Analytics - R
These are to be included in JWT in the response of `/recon/verify_token`
### 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/enums.rs b/crates/api_models/src/enums.rs
index c00afac6462..4af3f855d77 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -446,3 +446,20 @@ pub enum StripeChargeType {
pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> {
FrmConnectors::from_str(connector_name).ok()
}
+
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)]
+pub enum ReconPermissionScope {
+ #[serde(rename = "R")]
+ Read = 0,
+ #[serde(rename = "RW")]
+ Write = 1,
+}
+
+impl From<PermissionScope> for ReconPermissionScope {
+ fn from(scope: PermissionScope) -> Self {
+ match scope {
+ PermissionScope::Read => Self::Read,
+ PermissionScope::Write => Self::Write,
+ }
+ }
+}
diff --git a/crates/api_models/src/events/recon.rs b/crates/api_models/src/events/recon.rs
index aed648f4c86..596b0541282 100644
--- a/crates/api_models/src/events/recon.rs
+++ b/crates/api_models/src/events/recon.rs
@@ -1,6 +1,9 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
+use masking::PeekInterface;
-use crate::recon::{ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest};
+use crate::recon::{
+ ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse,
+};
impl ApiEventMetric for ReconUpdateMerchantRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -19,3 +22,11 @@ impl ApiEventMetric for ReconStatusResponse {
Some(ApiEventsType::Recon)
}
}
+
+impl ApiEventMetric for VerifyTokenResponse {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::User {
+ user_id: self.user_email.peek().to_string(),
+ })
+ }
+}
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 4dc2a1a301a..baac14e8afc 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -1,11 +1,7 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
-#[cfg(feature = "recon")]
-use masking::PeekInterface;
#[cfg(feature = "dummy_connector")]
use crate::user::sample_data::SampleDataRequest;
-#[cfg(feature = "recon")]
-use crate::user::VerifyTokenResponse;
use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
@@ -23,15 +19,6 @@ use crate::user::{
VerifyTotpRequest,
};
-#[cfg(feature = "recon")]
-impl ApiEventMetric for VerifyTokenResponse {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::User {
- user_id: self.user_email.peek().to_string(),
- })
- }
-}
-
common_utils::impl_api_event_type!(
Miscellaneous,
(
diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rs
index afee0fb5626..f73bcc5ae1f 100644
--- a/crates/api_models/src/recon.rs
+++ b/crates/api_models/src/recon.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{id_type, pii};
use masking::Secret;
use crate::enums;
@@ -18,3 +18,11 @@ pub struct ReconTokenResponse {
pub struct ReconStatusResponse {
pub recon_status: enums::ReconStatus,
}
+
+#[derive(serde::Serialize, Debug)]
+pub struct VerifyTokenResponse {
+ pub merchant_id: id_type::MerchantId,
+ pub user_email: pii::Email,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub acl: Option<String>,
+}
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 089426c68ba..9c70ea895ad 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -167,13 +167,6 @@ pub struct SendVerifyEmailRequest {
pub email: pii::Email,
}
-#[cfg(feature = "recon")]
-#[derive(serde::Serialize, Debug)]
-pub struct VerifyTokenResponse {
- pub merchant_id: id_type::MerchantId,
- pub user_email: pii::Email,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserAccountDetailsRequest {
pub name: Option<Secret<String>>,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 781b5e3710a..cb4281ee45c 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2819,9 +2819,15 @@ pub enum PermissionGroup {
MerchantDetailsManage,
// TODO: To be deprecated, make sure DB is migrated before removing
OrganizationManage,
- ReconOps,
AccountView,
AccountManage,
+ ReconReportsView,
+ ReconReportsManage,
+ ReconOpsView,
+ // Alias is added for backward compatibility with database
+ // TODO: Remove alias post migration
+ #[serde(alias = "recon_ops")]
+ ReconOpsManage,
}
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)]
@@ -2831,7 +2837,8 @@ pub enum ParentGroup {
Workflows,
Analytics,
Users,
- Recon,
+ ReconOps,
+ ReconReports,
Account,
}
@@ -2854,7 +2861,13 @@ pub enum Resource {
WebhookEvent,
Payout,
Report,
- Recon,
+ ReconToken,
+ ReconFiles,
+ ReconAndSettlementAnalytics,
+ ReconUpload,
+ ReconReports,
+ RunRecon,
+ ReconConfig,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)]
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs
index 521c978e3c2..13cf4c488ec 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -1,100 +1,113 @@
use api_models::recon as recon_api;
+#[cfg(feature = "email")]
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
+#[cfg(feature = "email")]
use masking::{ExposeInterface, PeekInterface, Secret};
+#[cfg(feature = "email")]
+use crate::{consts, services::email::types as email_types, types::domain};
use crate::{
- consts,
- core::errors::{self, RouterResponse, UserErrors},
- services::{api as service_api, authentication, email::types as email_types},
+ core::errors::{self, RouterResponse, UserErrors, UserResponse},
+ services::{api as service_api, authentication},
types::{
api::{self as api_types, enums},
- domain, storage,
+ storage,
transformers::ForeignTryFrom,
},
SessionState,
};
+#[allow(unused_variables)]
pub async fn send_recon_request(
state: SessionState,
auth_data: authentication::AuthenticationDataWithUser,
) -> RouterResponse<recon_api::ReconStatusResponse> {
- 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 {
- feature_name: consts::RECON_FEATURE_TAG.to_string(),
- merchant_id: merchant_id.clone(),
- user_name: domain::UserName::new(user_in_db.name.clone())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to form username")?,
- user_email: domain::UserEmail::from_pii_email(user_email.clone())
+ #[cfg(not(feature = "email"))]
+ return Ok(service_api::ApplicationResponse::Json(
+ recon_api::ReconStatusResponse {
+ recon_status: enums::ReconStatus::NotRequested,
+ },
+ ));
+
+ #[cfg(feature = "email")]
+ {
+ 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 {
+ feature_name: consts::RECON_FEATURE_TAG.to_string(),
+ merchant_id: merchant_id.clone(),
+ user_name: domain::UserName::new(user_in_db.name.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to form username")?,
+ user_email: domain::UserEmail::from_pii_email(user_email.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to convert recipient's email to UserEmail")?,
+ recipient_email: domain::UserEmail::from_pii_email(
+ state.conf.email.recon_recipient_email.clone(),
+ )
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert recipient's email to UserEmail")?,
- recipient_email: domain::UserEmail::from_pii_email(
- state.conf.email.recon_recipient_email.clone(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to convert recipient's email to UserEmail")?,
- settings: state.conf.clone(),
- subject: format!(
- "{} {}",
- consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,
- user_email.expose().peek()
- ),
- };
+ subject: format!(
+ "{} {}",
+ consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,
+ user_email.expose().peek()
+ ),
+ };
+ state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]")
+ .async_and_then(|_| async {
+ let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
+ recon_status: enums::ReconStatus::Requested,
+ };
+ let db = &*state.store;
+ let key_manager_state = &(&state).into();
- state
- .email_client
- .compose_and_send_email(
- Box::new(email_contents),
- state.conf.proxy.https_url.as_ref(),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]")
- .async_and_then(|_| async {
- let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
- recon_status: enums::ReconStatus::Requested,
- };
- let db = &*state.store;
- let key_manager_state = &(&state).into();
-
- let response = db
- .update_merchant(
- key_manager_state,
- auth_data.merchant_account,
- updated_merchant_account,
- &auth_data.key_store,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable_lazy(|| {
- format!("Failed while updating merchant's recon status: {merchant_id:?}")
- })?;
-
- Ok(service_api::ApplicationResponse::Json(
- recon_api::ReconStatusResponse {
- recon_status: response.recon_status,
- },
- ))
- })
- .await
+ let response = db
+ .update_merchant(
+ key_manager_state,
+ auth_data.merchant_account,
+ updated_merchant_account,
+ &auth_data.key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("Failed while updating merchant's recon status: {merchant_id:?}")
+ })?;
+
+ Ok(service_api::ApplicationResponse::Json(
+ recon_api::ReconStatusResponse {
+ recon_status: response.recon_status,
+ },
+ ))
+ })
+ .await
+ }
}
pub async fn generate_recon_token(
state: SessionState,
- user: authentication::UserFromToken,
+ user_with_role: authentication::UserFromTokenWithRoleInfo,
) -> RouterResponse<recon_api::ReconTokenResponse> {
- let token = authentication::AuthToken::new_token(
+ let user = user_with_role.user;
+ let token = authentication::ReconToken::new_token(
user.user_id.clone(),
user.merchant_id.clone(),
- user.role_id.clone(),
&state.conf,
user.org_id.clone(),
user.profile_id.clone(),
user.tenant_id,
+ user_with_role.role_info,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -138,29 +151,37 @@ pub async fn recon_merchant_account_update(
format!("Failed while updating merchant's recon status: {merchant_id:?}")
})?;
- let user_email = &req.user_email.clone();
- let email_contents = email_types::ReconActivation {
- recipient_email: domain::UserEmail::from_pii_email(user_email.clone())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to convert recipient's email to UserEmail from pii::Email")?,
- user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string()))
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to form username")?,
- settings: state.conf.clone(),
- subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,
- };
-
- if req.recon_status == enums::ReconStatus::Active {
- let _ = state
- .email_client
- .compose_and_send_email(
- Box::new(email_contents),
- state.conf.proxy.https_url.as_ref(),
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to compose and send email for ReconActivation")
- .is_ok();
+ #[cfg(feature = "email")]
+ {
+ let user_email = &req.user_email.clone();
+ let email_contents = email_types::ReconActivation {
+ recipient_email: domain::UserEmail::from_pii_email(user_email.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to convert recipient's email to UserEmail from pii::Email",
+ )?,
+ user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string()))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to form username")?,
+ subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,
+ };
+ if req.recon_status == enums::ReconStatus::Active {
+ let _ = state
+ .email_client
+ .compose_and_send_email(
+ Box::new(email_contents),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await
+ .inspect_err(|err| {
+ router_env::logger::error!(
+ "Failed to compose and send email notifying them of recon activation: {}",
+ err
+ )
+ })
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to compose and send email for ReconActivation");
+ }
}
Ok(service_api::ApplicationResponse::Json(
@@ -170,3 +191,34 @@ pub async fn recon_merchant_account_update(
})?,
))
}
+
+pub async fn verify_recon_token(
+ state: SessionState,
+ user_with_role: authentication::UserFromTokenWithRoleInfo,
+) -> UserResponse<recon_api::VerifyTokenResponse> {
+ let user = user_with_role.user;
+ let user_in_db = user
+ .get_user_from_db(&state)
+ .await
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to fetch the user from DB for user_id - {}",
+ user.user_id
+ )
+ })?;
+
+ let acl = user_with_role.role_info.get_recon_acl();
+ let optional_acl_str = serde_json::to_string(&acl)
+ .inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err))
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to serialize acl to string. Using empty ACL")
+ .ok();
+
+ Ok(service_api::ApplicationResponse::Json(
+ recon_api::VerifyTokenResponse {
+ merchant_id: user.merchant_id.to_owned(),
+ user_email: user_in_db.0.email,
+ acl: optional_acl_str,
+ },
+ ))
+}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 039e891e422..7ca4a127e85 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1593,27 +1593,6 @@ pub async fn send_verification_mail(
Ok(ApplicationResponse::StatusOk)
}
-#[cfg(feature = "recon")]
-pub async fn verify_token(
- state: SessionState,
- user: auth::UserFromToken,
-) -> UserResponse<user_api::VerifyTokenResponse> {
- let user_in_db = user
- .get_user_from_db(&state)
- .await
- .attach_printable_lazy(|| {
- format!(
- "Failed to fetch the user from DB for user_id - {}",
- user.user_id
- )
- })?;
-
- Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse {
- merchant_id: user.merchant_id.to_owned(),
- user_email: user_in_db.0.email,
- }))
-}
-
pub async fn update_user_details(
state: SessionState,
user_token: auth::UserFromToken,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bb8d0d4f2bd..3d1474ee81a 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1216,7 +1216,10 @@ impl Recon {
.service(
web::resource("/request").route(web::post().to(recon_routes::request_for_recon)),
)
- .service(web::resource("/verify_token").route(web::get().to(user::verify_recon_token)))
+ .service(
+ web::resource("/verify_token")
+ .route(web::get().to(recon_routes::verify_recon_token)),
+ )
}
}
diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs
index cdc2ae758e9..cfd076c7100 100644
--- a/crates/router/src/routes/recon.rs
+++ b/crates/router/src/routes/recon.rs
@@ -38,7 +38,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest
(),
|state, user, _, _| recon::send_recon_request(state, user),
&authentication::JWTAuth {
- permission: Permission::MerchantReconWrite,
+ permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -54,7 +54,24 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht
(),
|state, user, _, _| recon::generate_recon_token(state, user),
&authentication::JWTAuth {
- permission: Permission::MerchantReconWrite,
+ permission: Permission::MerchantReconTokenRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "recon")]
+pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
+ let flow = Flow::ReconVerifyToken;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &http_req,
+ (),
+ |state, user, _req, _| recon::verify_recon_token(state, user),
+ &authentication::JWTAuth {
+ permission: Permission::MerchantReconTokenRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 8fc0dad452a..af55f7f3055 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -487,23 +487,6 @@ pub async fn verify_email_request(
.await
}
-#[cfg(feature = "recon")]
-pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse {
- let flow = Flow::ReconVerifyToken;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &http_req,
- (),
- |state, user, _req, _| user_core::verify_token(state, user),
- &auth::JWTAuth {
- permission: Permission::MerchantReconWrite,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn update_user_account_details(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 1967eafd180..58253684a27 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -90,6 +90,12 @@ pub struct AuthenticationDataWithUser {
pub profile_id: id_type::ProfileId,
}
+#[derive(Clone)]
+pub struct UserFromTokenWithRoleInfo {
+ pub user: UserFromToken,
+ pub role_info: authorization::roles::RoleInfo,
+}
+
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(
tag = "api_auth_type",
@@ -3228,3 +3234,91 @@ where
Ok((auth, auth_type))
}
}
+
+#[cfg(feature = "recon")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(UserFromTokenWithRoleInfo, 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());
+ }
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
+ let role_info = authorization::get_role_info(state, &payload).await?;
+ authorization::check_permission(&self.permission, &role_info)?;
+
+ let user = UserFromToken {
+ user_id: payload.user_id.clone(),
+ merchant_id: payload.merchant_id.clone(),
+ org_id: payload.org_id,
+ role_id: payload.role_id,
+ profile_id: payload.profile_id,
+ tenant_id: payload.tenant_id,
+ };
+
+ Ok((
+ UserFromTokenWithRoleInfo { user, role_info },
+ AuthenticationType::MerchantJwt {
+ merchant_id: payload.merchant_id,
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+}
+
+#[cfg(feature = "recon")]
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct ReconToken {
+ pub user_id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub role_id: String,
+ pub exp: u64,
+ pub org_id: id_type::OrganizationId,
+ pub profile_id: id_type::ProfileId,
+ pub tenant_id: Option<id_type::TenantId>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub acl: Option<String>,
+}
+
+#[cfg(all(feature = "olap", feature = "recon"))]
+impl ReconToken {
+ pub async fn new_token(
+ user_id: String,
+ merchant_id: id_type::MerchantId,
+ settings: &Settings,
+ org_id: id_type::OrganizationId,
+ profile_id: id_type::ProfileId,
+ tenant_id: Option<id_type::TenantId>,
+ role_info: authorization::roles::RoleInfo,
+ ) -> UserResult<String> {
+ let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
+ let exp = jwt::generate_exp(exp_duration)?.as_secs();
+ let acl = role_info.get_recon_acl();
+ let optional_acl_str = serde_json::to_string(&acl)
+ .inspect_err(|err| logger::error!("Failed to serialize acl to string: {}", err))
+ .change_context(errors::UserErrors::InternalServerError)
+ .attach_printable("Failed to serialize acl to string. Using empty ACL")
+ .ok();
+ let token_payload = Self {
+ user_id,
+ merchant_id,
+ role_id: role_info.get_role_id().to_string(),
+ exp,
+ org_id,
+ profile_id,
+ tenant_id,
+ acl: optional_acl_str,
+ };
+ jwt::generate_jwt(&token_payload, settings).await
+ }
+}
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index bd987e2fe9a..2d808a4377a 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -40,7 +40,10 @@ fn get_group_description(group: PermissionGroup) -> &'static str {
PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details",
PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
- PermissionGroup::ReconOps => "View and manage reconciliation reports",
+ PermissionGroup::ReconReportsView => "View and access reconciliation reports and analytics",
+ PermissionGroup::ReconReportsManage => "Manage reconciliation reports",
+ PermissionGroup::ReconOpsView => "View and access reconciliation operations",
+ PermissionGroup::ReconOpsManage => "Manage reconciliation operations",
}
}
@@ -52,6 +55,7 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
ParentGroup::Analytics => "View Analytics",
ParentGroup::Users => "Manage and invite Users to the Team",
ParentGroup::Account => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
- ParentGroup::Recon => "View and manage reconciliation reports",
+ ParentGroup::ReconOps => "View, manage reconciliation operations like upload and process files, run reconciliation etc",
+ ParentGroup::ReconReports => "View, manage reconciliation reports and analytics",
}
}
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index 57c385565a8..7ca8442c1ce 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -21,7 +21,9 @@ impl PermissionGroupExt for PermissionGroup {
| Self::AnalyticsView
| Self::UsersView
| Self::MerchantDetailsView
- | Self::AccountView => PermissionScope::Read,
+ | Self::AccountView
+ | Self::ReconOpsView
+ | Self::ReconReportsView => PermissionScope::Read,
Self::OperationsManage
| Self::ConnectorsManage
@@ -29,8 +31,9 @@ impl PermissionGroupExt for PermissionGroup {
| Self::UsersManage
| Self::MerchantDetailsManage
| Self::OrganizationManage
- | Self::ReconOps
- | Self::AccountManage => PermissionScope::Write,
+ | Self::AccountManage
+ | Self::ReconOpsManage
+ | Self::ReconReportsManage => PermissionScope::Write,
}
}
@@ -41,12 +44,13 @@ impl PermissionGroupExt for PermissionGroup {
Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
Self::AnalyticsView => ParentGroup::Analytics,
Self::UsersView | Self::UsersManage => ParentGroup::Users,
- Self::ReconOps => ParentGroup::Recon,
Self::MerchantDetailsView
| Self::OrganizationManage
| Self::MerchantDetailsManage
| Self::AccountView
| Self::AccountManage => ParentGroup::Account,
+ Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,
+ Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,
}
}
@@ -76,7 +80,11 @@ impl PermissionGroupExt for PermissionGroup {
vec![Self::UsersView, Self::UsersManage]
}
- Self::ReconOps => vec![Self::ReconOps],
+ Self::ReconOpsView => vec![Self::ReconOpsView],
+ Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage],
+
+ Self::ReconReportsView => vec![Self::ReconReportsView],
+ Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage],
Self::MerchantDetailsView => vec![Self::MerchantDetailsView],
Self::MerchantDetailsManage => {
@@ -108,7 +116,8 @@ impl ParentGroupExt for ParentGroup {
Self::Analytics => ANALYTICS.to_vec(),
Self::Users => USERS.to_vec(),
Self::Account => ACCOUNT.to_vec(),
- Self::Recon => RECON.to_vec(),
+ Self::ReconOps => RECON_OPS.to_vec(),
+ Self::ReconReports => RECON_REPORTS.to_vec(),
}
}
@@ -167,4 +176,18 @@ pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];
pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];
-pub static RECON: [Resource; 1] = [Resource::Recon];
+pub static RECON_OPS: [Resource; 7] = [
+ Resource::ReconToken,
+ Resource::ReconFiles,
+ Resource::ReconUpload,
+ Resource::RunRecon,
+ Resource::ReconConfig,
+ Resource::ReconAndSettlementAnalytics,
+ Resource::ReconReports,
+];
+
+pub static RECON_REPORTS: [Resource; 3] = [
+ Resource::ReconToken,
+ Resource::ReconAndSettlementAnalytics,
+ Resource::ReconReports,
+];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 6e472d55623..6f612007425 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -67,8 +67,32 @@ generate_permissions! {
scopes: [Read, Write],
entities: [Merchant]
},
- Recon: {
- scopes: [Write],
+ ReconToken: {
+ scopes: [Read],
+ entities: [Merchant]
+ },
+ ReconFiles: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ ReconAndSettlementAnalytics: {
+ scopes: [Read],
+ entities: [Merchant]
+ },
+ ReconUpload: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ ReconReports: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ RunRecon: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ ReconConfig: {
+ scopes: [Read, Write],
entities: [Merchant]
},
]
@@ -91,7 +115,13 @@ pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'sta
(Resource::Report, _) => "Operation Reports",
(Resource::User, _) => "Users",
(Resource::WebhookEvent, _) => "Webhook Events",
- (Resource::Recon, _) => "Reconciliation Reports",
+ (Resource::ReconUpload, _) => "Reconciliation File Upload",
+ (Resource::RunRecon, _) => "Run Reconciliation Process",
+ (Resource::ReconConfig, _) => "Reconciliation Configurations",
+ (Resource::ReconToken, _) => "Generate & Verify Reconciliation Token",
+ (Resource::ReconFiles, _) => "Reconciliation Process Manager",
+ (Resource::ReconReports, _) => "Reconciliation Reports",
+ (Resource::ReconAndSettlementAnalytics, _) => "Reconciliation Analytics",
(Resource::Account, EntityType::Profile) => "Business Profile Account",
(Resource::Account, EntityType::Merchant) => "Merchant Account",
(Resource::Account, EntityType::Organization) => "Organization Account",
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index bf66eb92466..f6c4f4b9ef2 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -1,8 +1,14 @@
+#[cfg(feature = "recon")]
+use std::collections::HashMap;
use std::collections::HashSet;
+#[cfg(feature = "recon")]
+use api_models::enums::ReconPermissionScope;
use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
+#[cfg(feature = "recon")]
+use super::permission_groups::{RECON_OPS, RECON_REPORTS};
use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
@@ -78,6 +84,38 @@ impl RoleInfo {
})
}
+ #[cfg(feature = "recon")]
+ pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> {
+ let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new();
+ let mut recon_resources = RECON_OPS.to_vec();
+ recon_resources.extend(RECON_REPORTS);
+ let recon_internal_resources = [Resource::ReconToken];
+ self.get_permission_groups()
+ .iter()
+ .for_each(|permission_group| {
+ permission_group.resources().iter().for_each(|resource| {
+ if recon_resources.contains(resource)
+ && !recon_internal_resources.contains(resource)
+ {
+ let scope = match resource {
+ Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read,
+ _ => ReconPermissionScope::from(permission_group.scope()),
+ };
+ acl.entry(*resource)
+ .and_modify(|curr_scope| {
+ *curr_scope = if (*curr_scope) < scope {
+ scope
+ } else {
+ *curr_scope
+ }
+ })
+ .or_insert(scope);
+ }
+ })
+ });
+ acl
+ }
+
pub async fn from_role_id_in_merchant_scope(
state: &SessionState,
role_id: &str,
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 39f6d47f824..9c67c12f527 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -28,7 +28,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
- PermissionGroup::ReconOps,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconOpsManage,
+ PermissionGroup::ReconReportsView,
+ PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
@@ -51,6 +54,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconReportsView,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
@@ -82,7 +87,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
- PermissionGroup::ReconOps,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconOpsManage,
+ PermissionGroup::ReconReportsView,
+ PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
role_name: "organization_admin".to_string(),
@@ -113,7 +121,10 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
- PermissionGroup::ReconOps,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconOpsManage,
+ PermissionGroup::ReconReportsView,
+ PermissionGroup::ReconReportsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
role_name: "merchant_admin".to_string(),
@@ -136,6 +147,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
role_name: "merchant_view_only".to_string(),
@@ -180,6 +193,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
role_name: "merchant_developer".to_string(),
@@ -203,6 +218,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconOpsManage,
+ PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
role_name: "merchant_operator".to_string(),
@@ -223,6 +241,8 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
+ PermissionGroup::ReconOpsView,
+ PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
role_name: "customer_support".to_string(),
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 8c966d79d80..66e730f0824 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -383,7 +383,6 @@ impl EmailData for InviteUser {
pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
- pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
}
@@ -458,7 +457,6 @@ pub struct ProFeatureRequest {
pub merchant_id: common_utils::id_type::MerchantId,
pub user_name: domain::UserName,
pub user_email: domain::UserEmail,
- pub settings: std::sync::Arc<configs::Settings>,
pub subject: String,
}
|
2024-11-18T06:24:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #6524
This PR includes below changes
- Extending resources enum (for specifying the resource being consumed from the dashboard)
- Extending granular permission groups for recon
- Populating `acl` field in the recon token
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Helps maintain and configure permissions for recon module granularly.
## How did you test it?
- Verify the generated recon token has `acl`
- `GET /verify_token` response to have `acl`
<details>
<summary>Check /verify_token response</summary>
cURL
curl --location --request GET 'http://localhost:8080/recon/verify_token' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZGJjMzJmMmYtYmI5Ni00MDI0LTliYTUtNjhkOTc3MzM0N2U5IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMxOTk2NjQ4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjE4MzU4Miwib3JnX2lkIjoib3JnX0htMmY5dERZM2lGN0ZRckZUYUxKIiwicHJvZmlsZV9pZCI6InByb19GY0NaN1c4MllZVmNXMU1DSjZIOCIsInRlbmFudF9pZCI6InB1YmxpYyIsImFjbCI6IntcInJlY29uX2ZpbGVzXCI6XCJSV1wiLFwicmVjb25fY29uZmlnXCI6XCJSV1wiLFwicmVjb25fdG9rZW5cIjpcIlJXXCIsXCJyZWNvbl9yZXBvcnRzXCI6XCJSV1wiLFwicmVjb25fdXBsb2FkXCI6XCJSV1wiLFwicnVuX3JlY29uXCI6XCJSV1wiLFwicmVjb25fYW5kX3NldHRsZW1lbnRfYW5hbHl0aWNzXCI6XCJSXCJ9In0.wvS97F0dXwY7Y5uKSk8PEqHOhoAAPlR0coX_kIGyM2I'
Response
{
"merchant_id": "merchant_1731996648",
"user_email": "kashif2@juspay.in",
"acl": "{\"recon_reports\":\"RW\",\"recon_files\":\"RW\",\"run_recon\":\"RW\",\"recon_and_settlement_analytics\":\"R\",\"recon_token\":\"RW\",\"recon_upload\":\"RW\",\"recon_config\":\"RW\"}"
}
</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
79a75ce65418f21da7250e1538d0990047ba52d9
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6482
|
Bug: feat(users): Force users to reset password on first login for non-email flow
Currently in non-email flow, users who are invited are not forced to change their password.
This is being forced in email flow, this should also be present in non-email flow as well.
|
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 8331dff95c1..c48fe3320f3 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1,4 +1,8 @@
-use std::{collections::HashSet, ops, str::FromStr};
+use std::{
+ collections::HashSet,
+ ops::{Deref, Not},
+ str::FromStr,
+};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
@@ -153,7 +157,7 @@ impl TryFrom<pii::Email> for UserEmail {
}
}
-impl ops::Deref for UserEmail {
+impl Deref for UserEmail {
type Target = Secret<String, pii::EmailStrategy>;
fn deref(&self) -> &Self::Target {
@@ -565,10 +569,24 @@ pub struct NewUser {
user_id: String,
name: UserName,
email: UserEmail,
- password: Option<UserPassword>,
+ password: Option<NewUserPassword>,
new_merchant: NewUserMerchant,
}
+#[derive(Clone)]
+pub struct NewUserPassword {
+ password: UserPassword,
+ is_temporary: bool,
+}
+
+impl Deref for NewUserPassword {
+ type Target = UserPassword;
+
+ fn deref(&self) -> &Self::Target {
+ &self.password
+ }
+}
+
impl NewUser {
pub fn get_user_id(&self) -> String {
self.user_id.clone()
@@ -587,7 +605,9 @@ impl NewUser {
}
pub fn get_password(&self) -> Option<UserPassword> {
- self.password.clone()
+ self.password
+ .as_ref()
+ .map(|password| password.deref().clone())
}
pub async fn insert_user_in_db(
@@ -697,7 +717,9 @@ impl TryFrom<NewUser> for storage_user::UserNew {
totp_status: TotpStatus::NotSet,
totp_secret: None,
totp_recovery_codes: None,
- last_password_modified_at: value.password.is_some().then_some(now),
+ last_password_modified_at: value
+ .password
+ .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)),
})
}
}
@@ -708,7 +730,10 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser {
fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> {
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
- let password = UserPassword::new(value.password.clone())?;
+ let password = NewUserPassword {
+ password: UserPassword::new(value.password.clone())?,
+ is_temporary: false,
+ };
let user_id = uuid::Uuid::new_v4().to_string();
let new_merchant = NewUserMerchant::try_from(value)?;
@@ -729,7 +754,10 @@ impl TryFrom<user_api::SignUpRequest> for NewUser {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::try_from(value.email.clone())?;
- let password = UserPassword::new(value.password.clone())?;
+ let password = NewUserPassword {
+ password: UserPassword::new(value.password.clone())?,
+ is_temporary: false,
+ };
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
@@ -770,7 +798,10 @@ impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
- let password = UserPassword::new(value.password.clone())?;
+ let password = NewUserPassword {
+ password: UserPassword::new(value.password.clone())?,
+ is_temporary: false,
+ };
let new_merchant = NewUserMerchant::try_from((value, org_id))?;
Ok(Self {
@@ -789,16 +820,21 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser {
fn try_from(value: UserMerchantCreateRequestWithToken) -> Result<Self, Self::Error> {
let user = value.0.clone();
let new_merchant = NewUserMerchant::try_from(value)?;
+ let password = user
+ .0
+ .password
+ .map(UserPassword::new_password_without_validation)
+ .transpose()?
+ .map(|password| NewUserPassword {
+ password,
+ is_temporary: false,
+ });
Ok(Self {
user_id: user.0.user_id,
name: UserName::new(user.0.name)?,
email: user.0.email.clone().try_into()?,
- password: user
- .0
- .password
- .map(UserPassword::new_password_without_validation)
- .transpose()?,
+ password,
new_merchant,
})
}
@@ -810,8 +846,10 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.0.email.clone().try_into()?;
let name = UserName::new(value.0.name.clone())?;
- let password = cfg!(not(feature = "email"))
- .then_some(UserPassword::new(password::get_temp_password())?);
+ let password = cfg!(not(feature = "email")).then_some(NewUserPassword {
+ password: UserPassword::new(password::get_temp_password())?,
+ is_temporary: true,
+ });
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
|
2024-11-05T13:01:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently in non-email flow, users who are invited are not forced to change their password. This PR will add 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).
-->
Closes [#6482](https://github.com/juspay/hyperswitch/issues/6482).
## How did you test 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. Invite a new user in non-email flow
```
curl --location 'http://localhost:8080/user/user/invite_multiple?token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiN2I2NTA1NGQtNjgzNC00NzU2LTgyNDYtN2RkOWM1ZmQzMzRmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI5MTc4MDgzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDk4MzEyOSwib3JnX2lkIjoib3JnXzRiYWFjbHZxUklJTEl2a25NdnZQIiwicHJvZmlsZV9pZCI6InByb18yOUFWY0ltVnFDYTV1UHdMMzlQWCJ9.E5ZfkG5y0tqGa_vzGXe5LTJlyljqP8tKs1T2qokRtr0' \
--data-raw '[
{
"email": "new email",
"name": "name",
"role_id": "merchant_view_only"
}
]'
```
```json
[
{
"email": "email from request",
"is_email_sent": false,
"password": "4724b955-bc1d-4565-bbb6-1a09b2372bfaA"
}
]
```
2. Sign in as the new user
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email used in invite",
"password": "password from invite API response"
}'
```
```json
{
"token": "TOTP SPT",
"token_type": "totp"
}
```
3. Terminate 2FA (This API should give reset password SPT)
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: TOTP SPT' \
```
```json
{
"token": "Force set password SPT",
"token_type": "force_set_password"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
01c5216fdd6f1d841082868cccea6054b64e9e07
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6475
|
Bug: feat(opensearch): refactor global search querybuilder and add case insensitivity opensearch filters
- Currently the global search query builder logic is entirely present in a single function.
- With more and more features getting added on, it is better to separate out the logic to build the query into separate modules.
- Also, with the enhancement of global search, it is better to give out some fields as case sensitive and others as case insensitive.
Case Sensitive filters:
- customer_email
- payment_id
- card_last_4
- search_tags
Case Insensitive filters:
- payment_method
- payment_method_type
- card_network
- currency
- connector
- status
The new structure would be divided into separate functions for the respective modules as follows:
- Free Search Query + Time Range + Filters (case sensitive)
- Filters (case insensitive)
- Authentication and Search Params
|
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index a6e6c486ebe..84a2b9db3d4 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -1,3 +1,5 @@
+use std::collections::HashSet;
+
use api_models::{
analytics::search::SearchIndex,
errors::types::{ApiError, ApiErrorResponse},
@@ -456,7 +458,8 @@ pub struct OpenSearchQueryBuilder {
pub count: Option<i64>,
pub filters: Vec<(String, Vec<String>)>,
pub time_range: Option<OpensearchTimeRange>,
- pub search_params: Vec<AuthInfo>,
+ search_params: Vec<AuthInfo>,
+ case_sensitive_fields: HashSet<&'static str>,
}
impl OpenSearchQueryBuilder {
@@ -469,6 +472,12 @@ impl OpenSearchQueryBuilder {
count: Default::default(),
filters: Default::default(),
time_range: Default::default(),
+ case_sensitive_fields: HashSet::from([
+ "customer_email.keyword",
+ "search_tags.keyword",
+ "card_last_4.keyword",
+ "payment_id.keyword",
+ ]),
}
}
@@ -490,48 +499,16 @@ impl OpenSearchQueryBuilder {
pub fn get_status_field(&self, index: &SearchIndex) -> &str {
match index {
- SearchIndex::Refunds => "refund_status.keyword",
- SearchIndex::Disputes => "dispute_status.keyword",
+ SearchIndex::Refunds | SearchIndex::SessionizerRefunds => "refund_status.keyword",
+ SearchIndex::Disputes | SearchIndex::SessionizerDisputes => "dispute_status.keyword",
_ => "status.keyword",
}
}
- pub fn replace_status_field(&self, filters: &[Value], index: &SearchIndex) -> Vec<Value> {
- filters
- .iter()
- .map(|filter| {
- if let Some(terms) = filter.get("terms").and_then(|v| v.as_object()) {
- let mut new_filter = filter.clone();
- if let Some(new_terms) =
- new_filter.get_mut("terms").and_then(|v| v.as_object_mut())
- {
- let key = "status.keyword";
- if let Some(status_terms) = terms.get(key) {
- new_terms.remove(key);
- new_terms.insert(
- self.get_status_field(index).to_string(),
- status_terms.clone(),
- );
- }
- }
- new_filter
- } else {
- filter.clone()
- }
- })
- .collect()
- }
-
- /// # Panics
- ///
- /// This function will panic if:
- ///
- /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types).
- ///
- /// Ensure that the input data and the structure of the query are valid and correctly handled.
- pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> {
- let mut query_obj = Map::new();
- let mut bool_obj = Map::new();
+ pub fn build_filter_array(
+ &self,
+ case_sensitive_filters: Vec<&(String, Vec<String>)>,
+ ) -> Vec<Value> {
let mut filter_array = Vec::new();
filter_array.push(json!({
@@ -542,13 +519,12 @@ impl OpenSearchQueryBuilder {
}
}));
- let mut filters = self
- .filters
- .iter()
+ let case_sensitive_json_filters = case_sensitive_filters
+ .into_iter()
.map(|(k, v)| json!({"terms": {k: v}}))
.collect::<Vec<Value>>();
- filter_array.append(&mut filters);
+ filter_array.extend(case_sensitive_json_filters);
if let Some(ref time_range) = self.time_range {
let range = json!(time_range);
@@ -559,8 +535,72 @@ impl OpenSearchQueryBuilder {
}));
}
- let should_array = self
- .search_params
+ filter_array
+ }
+
+ pub fn build_case_insensitive_filters(
+ &self,
+ mut payload: Value,
+ case_insensitive_filters: &[&(String, Vec<String>)],
+ auth_array: Vec<Value>,
+ index: &SearchIndex,
+ ) -> Value {
+ let mut must_array = case_insensitive_filters
+ .iter()
+ .map(|(k, v)| {
+ let key = if *k == "status.keyword" {
+ self.get_status_field(index).to_string()
+ } else {
+ k.clone()
+ };
+ json!({
+ "bool": {
+ "must": [
+ {
+ "bool": {
+ "should": v.iter().map(|value| {
+ json!({
+ "term": {
+ format!("{}", key): {
+ "value": value,
+ "case_insensitive": true
+ }
+ }
+ })
+ }).collect::<Vec<Value>>(),
+ "minimum_should_match": 1
+ }
+ }
+ ]
+ }
+ })
+ })
+ .collect::<Vec<Value>>();
+
+ must_array.push(json!({ "bool": {
+ "must": [
+ {
+ "bool": {
+ "should": auth_array,
+ "minimum_should_match": 1
+ }
+ }
+ ]
+ }}));
+
+ if let Some(query) = payload.get_mut("query") {
+ if let Some(bool_obj) = query.get_mut("bool") {
+ if let Some(bool_map) = bool_obj.as_object_mut() {
+ bool_map.insert("must".to_string(), Value::Array(must_array));
+ }
+ }
+ }
+
+ payload
+ }
+
+ pub fn build_auth_array(&self) -> Vec<Value> {
+ self.search_params
.iter()
.map(|user_level| match user_level {
AuthInfo::OrgLevel { org_id } => {
@@ -579,11 +619,17 @@ impl OpenSearchQueryBuilder {
})
}
AuthInfo::MerchantLevel {
- org_id: _,
+ org_id,
merchant_ids,
} => {
let must_clauses = vec![
- // TODO: Add org_id field to the filters
+ json!({
+ "term": {
+ "organization_id.keyword": {
+ "value": org_id
+ }
+ }
+ }),
json!({
"terms": {
"merchant_id.keyword": merchant_ids
@@ -598,12 +644,18 @@ impl OpenSearchQueryBuilder {
})
}
AuthInfo::ProfileLevel {
- org_id: _,
+ org_id,
merchant_id,
profile_ids,
} => {
let must_clauses = vec![
- // TODO: Add org_id field to the filters
+ json!({
+ "term": {
+ "organization_id.keyword": {
+ "value": org_id
+ }
+ }
+ }),
json!({
"term": {
"merchant_id.keyword": {
@@ -625,55 +677,60 @@ impl OpenSearchQueryBuilder {
})
}
})
- .collect::<Vec<Value>>();
+ .collect::<Vec<Value>>()
+ }
+
+ /// # Panics
+ ///
+ /// This function will panic if:
+ ///
+ /// * The structure of the JSON query is not as expected (e.g., missing keys or incorrect types).
+ ///
+ /// Ensure that the input data and the structure of the query are valid and correctly handled.
+ pub fn construct_payload(&self, indexes: &[SearchIndex]) -> QueryResult<Vec<Value>> {
+ let mut query_obj = Map::new();
+ let mut bool_obj = Map::new();
+
+ let (case_sensitive_filters, case_insensitive_filters): (Vec<_>, Vec<_>) = self
+ .filters
+ .iter()
+ .partition(|(k, _)| self.case_sensitive_fields.contains(k.as_str()));
+
+ let filter_array = self.build_filter_array(case_sensitive_filters);
if !filter_array.is_empty() {
bool_obj.insert("filter".to_string(), Value::Array(filter_array));
}
+
+ let should_array = self.build_auth_array();
+
if !bool_obj.is_empty() {
query_obj.insert("bool".to_string(), Value::Object(bool_obj));
}
- let mut query = Map::new();
- query.insert("query".to_string(), Value::Object(query_obj));
+ let mut sort_obj = Map::new();
+ sort_obj.insert(
+ "@timestamp".to_string(),
+ json!({
+ "order": "desc"
+ }),
+ );
Ok(indexes
.iter()
.map(|index| {
- let updated_query = query
- .get("query")
- .and_then(|q| q.get("bool"))
- .and_then(|b| b.get("filter"))
- .and_then(|f| f.as_array())
- .map(|filters| self.replace_status_field(filters, index))
- .unwrap_or_default();
- let mut final_bool_obj = Map::new();
- if !updated_query.is_empty() {
- final_bool_obj.insert("filter".to_string(), Value::Array(updated_query));
- }
- if !should_array.is_empty() {
- final_bool_obj.insert("should".to_string(), Value::Array(should_array.clone()));
- final_bool_obj
- .insert("minimum_should_match".to_string(), Value::Number(1.into()));
- }
- let mut final_query = Map::new();
- if !final_bool_obj.is_empty() {
- final_query.insert("bool".to_string(), Value::Object(final_bool_obj));
- }
-
- let mut sort_obj = Map::new();
- sort_obj.insert(
- "@timestamp".to_string(),
- json!({
- "order": "desc"
- }),
- );
- let payload = json!({
- "query": Value::Object(final_query),
+ let mut payload = json!({
+ "query": query_obj.clone(),
"sort": [
- Value::Object(sort_obj)
+ Value::Object(sort_obj.clone())
]
});
+ payload = self.build_case_insensitive_filters(
+ payload,
+ &case_insensitive_filters,
+ should_array.clone(),
+ index,
+ );
payload
})
.collect::<Vec<Value>>())
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index f53b07b1232..9be0200030d 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -190,7 +190,17 @@ pub async fn search_results(
search_params: Vec<AuthInfo>,
) -> CustomResult<GetSearchResponse, OpenSearchError> {
let search_req = req.search_req;
-
+ if search_req.query.trim().is_empty()
+ && search_req
+ .filters
+ .as_ref()
+ .map_or(true, |filters| filters.is_all_none())
+ {
+ return Err(OpenSearchError::BadRequestError(
+ "Both query and filters are empty".to_string(),
+ )
+ .into());
+ }
let mut query_builder = OpenSearchQueryBuilder::new(
OpenSearchQuery::Search(req.index),
search_req.query,
|
2024-11-04T11:59:47Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Currently the global search query builder logic is entirely present in a single function.
- With more and more features getting added on, it is better to separate out the logic to build the query into separate modules.
- Also, with the enhancement of global search, it is better to give out some fields as case sensitive and others as case insensitive.
Case Sensitive filters:
- customer_email
- payment_id
- card_last_4
- search_tags
Case Insensitive filters:
- payment_method
- payment_method_type
- card_network
- currency
- connector
- status
The new structure would be divided into separate functions for the respective modules as follows:
- Free Search Query + Time Range + Filters (case sensitive)
- Filters (case insensitive)
- Authentication and Search Params
The query generated to hit opensearch will now look like the following:
```json
{
"query": {
"bool": {
"filter": [
{
"multi_match": {
"type": "phrase",
"query": "merchant_1726046328",
"lenient": true
}
},
{
"terms": {
"customer_email.keyword": [
"f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303"
]
}
},
{
"terms": {
"card_last_4.keyword": [
"4242"
]
}
},
{
"terms": {
"payment_id.keyword": [
"pay_QdstJpRVAcRKHzRIRK4d"
]
}
},
{
"range": {
"@timestamp": {
"gte": "2024-09-13T00:30:00.000Z",
"lte": "2024-10-30T21:45:00.000Z"
}
}
}
],
"must": [
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"currency.keyword": {
"value": "UsD",
"case_insensitive": true
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"status.keyword": {
"value": "CharGed",
"case_insensitive": true
}
}
},
{
"term": {
"status.keyword": {
"value": "succeeded",
"case_insensitive": true
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"payment_method.keyword": {
"value": "cArd",
"case_insensitive": true
}
}
},
{
"term": {
"payment_method.keyword": {
"value": "iwubefi",
"case_insensitive": true
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"connector.keyword": {
"value": "striPe_Test",
"case_insensitive": true
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"payment_method_type.keyword": {
"value": "credit",
"case_insensitive": true
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
{
"bool": {
"must": [
{
"bool": {
"should": [
{
"bool": {
"must": [
{
"term": {
"organization_id.keyword": {
"value": "org_VpSHOjsYfDvabVYJgCAJ"
}
}
}
]
}
}
],
"minimum_should_match": 1
}
}
]
}
}
]
}
},
"sort": [
{
"@timestamp": {
"order": "desc"
}
}
]
}
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Enhanced search experience based on free search and specific filters using global search.
- Can now search via filters in a case-insensitive manner for some common filters.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Can send the following filters in any case:
- payment_method
- payment_method_type
- card_network
- currency
- connector
- status
Must send the following filters in the exact case:
- customer_email
- payment_id
- card_last_4
- search_tags
#### Hit the curl:
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--header 'sec-ch-ua-platform: "macOS"' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDg3MDI4Niwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.luU7VDVnDVz7xuHLKEY5UWfxU78sGvzysZ99R8-1Bxo' \
--header 'Referer: http://localhost:9000/' \
--header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--data-raw '{
"query": "merchant_1726046328",
"filters": {
"currency": [
"UsD"
],
"connector": [
"striPe_Test"
],
"customer_email": [
"test@test14.com"
],
"payment_method_type": [
"credit"
],
"payment_method": [
"cArd", "iwubefi"
],
"payment_id": [
"pay_QdstJpRVAcRKHzRIRK4d"
],
"card_last_4": [
"4242"
],
"status": [
"CharGed", "succeeded"
]
},
"timeRange": {
"startTime": "2024-09-13T00:30:00Z",
"endTime": "2024-10-30T21:45:00Z"
}
}'
```
Expected response:
```json
[
{
"count": 0,
"index": "payment_attempts",
"hits": [],
"status": "Success"
},
{
"count": 0,
"index": "payment_intents",
"hits": [],
"status": "Success"
},
{
"count": 0,
"index": "refunds",
"hits": [],
"status": "Success"
},
{
"count": 0,
"index": "disputes",
"hits": [],
"status": "Failure"
},
{
"count": 1,
"index": "sessionizer_payment_attempts",
"hits": [
{
"@timestamp": "2024-10-24T07:59:12.887Z",
"amount": 6540,
"amount_capturable": 0,
"amount_to_capture": 6540,
"attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1",
"authentication_type": "no_three_ds",
"capture_method": "automatic",
"capture_on": 1662804672000,
"card_last_4": "4242",
"confirm": true,
"connector": "stripe_test",
"connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ",
"created_at": 1729756752887,
"currency": "USD",
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"customer_id": "StripeCustomer",
"first_attempt": true,
"headers": {},
"log_count": 9,
"merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6",
"merchant_id": "merchant_1726046328",
"modified_at": 1729756754123,
"net_amount": 6540,
"organization_id": "org_VpSHOjsYfDvabVYJgCAJ",
"payment_id": "pay_QdstJpRVAcRKHzRIRK4d",
"payment_method": "card",
"payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}",
"payment_method_type": "credit",
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"source_type": "kafka",
"status": "charged",
"tenant_id": "public",
"timestamp": "2024-10-24T07:59:12.887Z"
}
],
"status": "Success"
},
{
"count": 1,
"index": "sessionizer_payment_intents",
"hits": [
{
"@timestamp": "2024-10-24T07:59:12.886Z",
"active_attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1",
"amount": 6540,
"amount_captured": 6540,
"attempt_count": 1,
"attempts_list": [
{
"amount": 6540,
"amount_capturable": 0,
"amount_to_capture": 6540,
"attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1",
"authentication_type": "no_three_ds",
"capture_method": "automatic",
"capture_on": 1662804672000,
"confirm": true,
"connector": "stripe_test",
"connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ",
"created_at": 1729756752887,
"currency": "USD",
"last_synced": 1729756752887,
"merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6",
"merchant_id": "merchant_1726046328",
"modified_at": 1729756754123,
"net_amount": 6540,
"organization_id": "org_VpSHOjsYfDvabVYJgCAJ",
"payment_id": "pay_QdstJpRVAcRKHzRIRK4d",
"payment_method": "card",
"payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}",
"payment_method_type": "credit",
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"status": "charged",
"tenant_id": "public"
}
],
"authentication_type": "no_three_ds",
"business_label": "default",
"card_last_4": "4242",
"client_secret": "pay_QdstJpRVAcRKHzRIRK4d_secret_u2WJTHVO3BmpJfkzdXaY",
"connector": "stripe_test",
"created_at": 1729756752886,
"currency": "USD",
"customer_email": "f6cd0753a831880835a0e0d23136ef66318d8303605bd37fa80b4ecf248bd303",
"customer_id": "StripeCustomer",
"description": "Its my first payment request",
"dispute_list": [],
"headers": {},
"log_count": 9,
"merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6",
"merchant_id": "merchant_1726046328",
"metadata": "{\"data2\":\"camel\",\"login_date\":\"2019-09-10T10:11:12Z\",\"new_customer\":\"true\"}",
"modified_at": 1729756754123,
"organization_id": "org_VpSHOjsYfDvabVYJgCAJ",
"payment_id": "pay_QdstJpRVAcRKHzRIRK4d",
"payment_method": "card",
"payment_method_data": "{\"card\":{\"last4\":\"4242\",\"bank_code\":null,\"card_isin\":\"424242\",\"card_type\":null,\"card_issuer\":null,\"card_network\":null,\"card_exp_year\":\"25\",\"card_exp_month\":\"10\",\"payment_checks\":null,\"card_holder_name\":null,\"card_extended_bin\":null,\"authentication_data\":null,\"card_issuing_country\":null}}",
"payment_method_type": "credit",
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"refund_list": [
{
"attempt_id": "pay_QdstJpRVAcRKHzRIRK4d_1",
"connector": "stripe_test",
"connector_refund_id": "dummy_ref_6HyIEJcmDyE75QiFnv76",
"connector_transaction_id": "pay_BV1cUypv6paxZvJl2SiQ",
"created_at": 1729756766669,
"currency": "USD",
"description": "Customer returned product",
"external_reference_id": "ref_Tc3KfBVm5HEuzECytr9g",
"internal_reference_id": "refid_vDztMj3wI0ETCFXEoWUG",
"merchant_id": "merchant_1726046328",
"modified_at": 1729756767668,
"organization_id": "org_VpSHOjsYfDvabVYJgCAJ",
"payment_id": "pay_QdstJpRVAcRKHzRIRK4d",
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"refund_amount": 600,
"refund_arn": "",
"refund_id": "ref_Tc3KfBVm5HEuzECytr9g",
"refund_reason": "Customer returned product",
"refund_status": "success",
"refund_type": "instant_refund",
"sent_to_gateway": true,
"tenant_id": "public",
"total_amount": 6540
}
],
"refunds_status": "partial_refunded",
"return_url": "https://google.com/",
"source_type": "kafka",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"status": "succeeded",
"tenant_id": "public",
"timestamp": "2024-10-24T07:59:12.886Z"
}
],
"status": "Success"
},
{
"count": 0,
"index": "sessionizer_refunds",
"hits": [],
"status": "Success"
},
{
"count": 0,
"index": "sessionizer_disputes",
"hits": [],
"status": "Failure"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
72ee434003eef744d516343a2f803264f226d92a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6488
|
Bug: feat(users): Add profile level custom role
Currently only merchant level custom role is allowed with role scope as Merchant and organization
The requirement is to add profile level custom role at Organization , Merchant and Profile scope
|
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 7c877cd7477..46e15aafc70 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -7,6 +7,7 @@ pub struct CreateRoleRequest {
pub role_name: String,
pub groups: Vec<PermissionGroup>,
pub role_scope: RoleScope,
+ pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -21,6 +22,7 @@ pub struct RoleInfoWithGroupsResponse {
pub groups: Vec<PermissionGroup>,
pub role_name: String,
pub role_scope: RoleScope,
+ pub entity_type: Option<EntityType>,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 917030c1e80..e645b884677 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2679,6 +2679,8 @@ pub enum TransactionType {
Debug,
Eq,
PartialEq,
+ Ord,
+ PartialOrd,
serde::Deserialize,
serde::Serialize,
strum::Display,
@@ -2688,8 +2690,19 @@ pub enum TransactionType {
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoleScope {
- Merchant,
- Organization,
+ Organization = 2,
+ Merchant = 1,
+ Profile = 0,
+}
+
+impl From<RoleScope> for EntityType {
+ fn from(role_scope: RoleScope) -> Self {
+ match role_scope {
+ RoleScope::Organization => Self::Organization,
+ RoleScope::Merchant => Self::Merchant,
+ RoleScope::Profile => Self::Profile,
+ }
+ }
}
/// Indicates the transaction status
@@ -3132,6 +3145,7 @@ pub enum ApiVersion {
serde::Serialize,
strum::Display,
strum::EnumString,
+ strum::EnumIter,
ToSchema,
Hash,
)]
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 065a5b6e114..07d2cf2f0a1 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -1,4 +1,5 @@
use async_bb8_diesel::AsyncRunQueryDsl;
+use common_enums::EntityType;
use common_utils::id_type;
use diesel::{
associations::HasTable, debug_query, pg::Pg, result::Error as DieselError,
@@ -106,7 +107,7 @@ impl Role {
conn: &PgPooledConn,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
- entity_type: Option<common_enums::EntityType>,
+ entity_type: Option<EntityType>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
@@ -131,6 +132,97 @@ impl Role {
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+ match generics::db_metrics::track_database_call::<Self, _, _>(
+ query.get_results_async(conn),
+ generics::db_metrics::DatabaseOperation::Filter,
+ )
+ .await
+ {
+ Ok(value) => Ok(value),
+ Err(err) => match err {
+ DieselError::NotFound => {
+ Err(report!(err)).change_context(errors::DatabaseError::NotFound)
+ }
+ _ => Err(report!(err)).change_context(errors::DatabaseError::Others),
+ },
+ }
+ }
+ pub async fn generic_list_roles_by_entity_type(
+ conn: &PgPooledConn,
+ entity_type: ListRolesByEntityPayload,
+ is_lineage_data_required: bool,
+ limit: Option<u32>,
+ ) -> StorageResult<Vec<Self>> {
+ let mut query = <Self as HasTable>::table().into_boxed();
+
+ match entity_type {
+ ListRolesByEntityPayload::Organization(org_id) => {
+ let entity_in_vec = if is_lineage_data_required {
+ vec![
+ EntityType::Organization,
+ EntityType::Merchant,
+ EntityType::Profile,
+ ]
+ } else {
+ vec![EntityType::Organization]
+ };
+ query = query
+ .filter(dsl::org_id.eq(org_id))
+ .filter(
+ dsl::scope
+ .eq(RoleScope::Organization)
+ .or(dsl::scope.eq(RoleScope::Merchant))
+ .or(dsl::scope.eq(RoleScope::Profile)),
+ )
+ .filter(dsl::entity_type.eq_any(entity_in_vec))
+ }
+
+ ListRolesByEntityPayload::Merchant(org_id, merchant_id) => {
+ let entity_in_vec = if is_lineage_data_required {
+ vec![EntityType::Merchant, EntityType::Profile]
+ } else {
+ vec![EntityType::Merchant]
+ };
+ query = query
+ .filter(dsl::org_id.eq(org_id))
+ .filter(
+ dsl::scope
+ .eq(RoleScope::Organization)
+ .or(dsl::scope
+ .eq(RoleScope::Merchant)
+ .and(dsl::merchant_id.eq(merchant_id.clone())))
+ .or(dsl::scope
+ .eq(RoleScope::Profile)
+ .and(dsl::merchant_id.eq(merchant_id))),
+ )
+ .filter(dsl::entity_type.eq_any(entity_in_vec))
+ }
+
+ ListRolesByEntityPayload::Profile(org_id, merchant_id, profile_id) => {
+ let entity_in_vec = vec![EntityType::Profile];
+ query = query
+ .filter(dsl::org_id.eq(org_id))
+ .filter(
+ dsl::scope
+ .eq(RoleScope::Organization)
+ .or(dsl::scope
+ .eq(RoleScope::Merchant)
+ .and(dsl::merchant_id.eq(merchant_id.clone())))
+ .or(dsl::scope
+ .eq(RoleScope::Profile)
+ .and(dsl::merchant_id.eq(merchant_id))
+ .and(dsl::profile_id.eq(profile_id))),
+ )
+ .filter(dsl::entity_type.eq_any(entity_in_vec))
+ }
+ };
+
+ 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, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index 8199bd3979c..d96421f2db8 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -19,6 +19,7 @@ pub struct Role {
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
+ pub profile_id: Option<id_type::ProfileId>,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -36,6 +37,7 @@ pub struct RoleNew {
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
pub entity_type: enums::EntityType,
+ pub profile_id: Option<id_type::ProfileId>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
@@ -73,3 +75,13 @@ impl From<RoleUpdate> for RoleUpdateInternal {
}
}
}
+
+pub enum ListRolesByEntityPayload {
+ Profile(
+ id_type::OrganizationId,
+ id_type::MerchantId,
+ id_type::ProfileId,
+ ),
+ Merchant(id_type::OrganizationId, id_type::MerchantId),
+ Organization(id_type::OrganizationId),
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e2ab676b2d3..fd3752cecc9 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1236,6 +1236,8 @@ diesel::table! {
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 5651bf95dd9..c694751f5bd 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1182,6 +1182,8 @@ diesel::table! {
last_modified_by -> Varchar,
#[max_length = 64]
entity_type -> Varchar,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 0250415d4fd..48f5faccc58 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -3,7 +3,7 @@ use std::collections::HashSet;
use api_models::user_role::role::{self as role_api};
use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope};
use common_utils::generate_id_with_default_len;
-use diesel_models::role::{RoleNew, RoleUpdate};
+use diesel_models::role::{ListRolesByEntityPayload, RoleNew, RoleUpdate};
use error_stack::{report, ResultExt};
use crate::{
@@ -65,6 +65,39 @@ pub async fn create_role(
_req_state: ReqState,
) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let now = common_utils::date_time::now();
+
+ let user_entity_type = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?
+ .get_entity_type();
+
+ let role_entity_type = req.entity_type.unwrap_or(EntityType::Merchant);
+
+ if matches!(role_entity_type, EntityType::Organization) {
+ return Err(report!(UserErrors::InvalidRoleOperation))
+ .attach_printable("User trying to create org level custom role");
+ }
+
+ let requestor_entity_from_role_scope = EntityType::from(req.role_scope);
+
+ if !(user_entity_type >= role_entity_type) {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "{} is trying to create {} ",
+ user_entity_type, role_entity_type
+ ));
+ } else if !(user_entity_type >= requestor_entity_from_role_scope) {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "{} is trying to create role of scope {} ",
+ user_entity_type, requestor_entity_from_role_scope
+ ));
+ } else if !(requestor_entity_from_role_scope >= role_entity_type) {
+ return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "User is trying to create role of type {} and scope {}",
+ requestor_entity_from_role_scope, role_entity_type
+ ));
+ }
+
let role_name = RoleName::new(req.role_name)?;
utils::user_role::validate_role_groups(&req.groups)?;
@@ -76,12 +109,9 @@ pub async fn create_role(
)
.await?;
- if matches!(req.role_scope, RoleScope::Organization)
- && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN
- {
- return Err(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("Non org admin user creating org level role");
- }
+ let profile_id = matches!(role_entity_type, EntityType::Profile)
+ .then_some(user_from_token.profile_id)
+ .flatten();
let role = state
.store
@@ -92,11 +122,12 @@ pub async fn create_role(
org_id: user_from_token.org_id,
groups: req.groups,
scope: req.role_scope,
- entity_type: EntityType::Merchant,
+ entity_type: role_entity_type,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
last_modified_at: now,
+ profile_id,
})
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
@@ -107,6 +138,7 @@ pub async fn create_role(
role_id: role.role_id,
role_name: role.role_name,
role_scope: role.scope,
+ entity_type: Some(role.entity_type),
},
))
}
@@ -135,6 +167,7 @@ pub async fn get_role_with_groups(
role_id: role.role_id,
role_name: role_info.get_role_name().to_string(),
role_scope: role_info.get_scope(),
+ entity_type: Some(role_info.get_entity_type()),
},
))
}
@@ -245,6 +278,7 @@ pub async fn update_role(
role_id: updated_role.role_id,
role_name: updated_role.role_name,
role_scope: updated_role.scope,
+ entity_type: Some(updated_role.entity_type),
},
))
}
@@ -276,10 +310,9 @@ pub async fn list_roles_with_info(
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,
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Organization(user_from_token.org_id),
+ request.entity_type.is_none(),
None,
)
.await
@@ -287,17 +320,37 @@ pub async fn list_roles_with_info(
.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,
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Merchant(
+ user_from_token.org_id,
+ user_from_token.merchant_id,
+ ),
+ request.entity_type.is_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::Profile => {
+ let Some(profile_id) = user_from_token.profile_id else {
+ return Err(UserErrors::JwtProfileIdMissing.into());
+ };
+ state
+ .store
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Profile(
+ user_from_token.org_id,
+ user_from_token.merchant_id,
+ profile_id,
+ ),
+ request.entity_type.is_none(),
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?
+ }
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
@@ -349,10 +402,9 @@ pub async fn list_roles_at_entity_level(
let custom_roles = match req.entity_type {
EntityType::Organization => state
.store
- .list_roles_for_org_by_parameters(
- &user_from_token.org_id,
- None,
- Some(req.entity_type),
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Organization(user_from_token.org_id),
+ false,
None,
)
.await
@@ -361,17 +413,38 @@ pub async fn list_roles_at_entity_level(
EntityType::Merchant => state
.store
- .list_roles_for_org_by_parameters(
- &user_from_token.org_id,
- Some(&user_from_token.merchant_id),
- Some(req.entity_type),
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Merchant(
+ user_from_token.org_id,
+ user_from_token.merchant_id,
+ ),
+ false,
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::Profile => {
+ let Some(profile_id) = user_from_token.profile_id else {
+ return Err(UserErrors::JwtProfileIdMissing.into());
+ };
+
+ state
+ .store
+ .generic_list_roles_by_entity_type(
+ ListRolesByEntityPayload::Profile(
+ user_from_token.org_id,
+ user_from_token.merchant_id,
+ profile_id,
+ ),
+ false,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?
+ }
};
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 8ca0b293766..58c439c7371 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3534,6 +3534,17 @@ impl RoleInterface for KafkaStore {
.list_roles_for_org_by_parameters(org_id, merchant_id, entity_type, limit)
.await
}
+
+ async fn generic_list_roles_by_entity_type(
+ &self,
+ entity_type: diesel_models::role::ListRolesByEntityPayload,
+ is_lineage_data_required: bool,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ self.diesel_store
+ .generic_list_roles_by_entity_type(entity_type, is_lineage_data_required, limit)
+ .await
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index d13508356e5..4ec50de023d 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -1,6 +1,8 @@
-use common_enums::enums;
use common_utils::id_type;
-use diesel_models::role as storage;
+use diesel_models::{
+ enums::{EntityType, RoleScope},
+ role as storage,
+};
use error_stack::report;
use router_env::{instrument, tracing};
@@ -57,7 +59,14 @@ pub trait RoleInterface {
&self,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
- entity_type: Option<enums::EntityType>,
+ entity_type: Option<EntityType>,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
+
+ async fn generic_list_roles_by_entity_type(
+ &self,
+ entity_type: storage::ListRolesByEntityPayload,
+ is_lineage_data_required: bool,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
}
@@ -151,7 +160,7 @@ impl RoleInterface for Store {
&self,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
- entity_type: Option<enums::EntityType>,
+ entity_type: Option<EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -165,6 +174,24 @@ impl RoleInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ #[instrument(skip_all)]
+ async fn generic_list_roles_by_entity_type(
+ &self,
+ entity_type: storage::ListRolesByEntityPayload,
+ is_lineage_data_required: bool,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Role::generic_list_roles_by_entity_type(
+ &conn,
+ entity_type,
+ is_lineage_data_required,
+ limit,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -195,6 +222,7 @@ impl RoleInterface for MockDb {
created_at: role.created_at,
last_modified_at: role.last_modified_at,
last_modified_by: role.last_modified_by,
+ profile_id: role.profile_id,
};
roles.push(role.clone());
Ok(role)
@@ -229,7 +257,7 @@ impl RoleInterface for MockDb {
.find(|role| {
role.role_id == role_id
&& (role.merchant_id == *merchant_id
- || (role.org_id == *org_id && role.scope == enums::RoleScope::Organization))
+ || (role.org_id == *org_id && role.scope == RoleScope::Organization))
})
.cloned()
.ok_or(
@@ -319,8 +347,7 @@ impl RoleInterface for MockDb {
.iter()
.filter(|role| {
role.merchant_id == *merchant_id
- || (role.org_id == *org_id
- && role.scope == diesel_models::enums::RoleScope::Organization)
+ || (role.org_id == *org_id && role.scope == RoleScope::Organization)
})
.cloned()
.collect();
@@ -341,7 +368,7 @@ impl RoleInterface for MockDb {
&self,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
- entity_type: Option<enums::EntityType>,
+ entity_type: Option<EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let roles = self.roles.lock().await;
@@ -362,4 +389,83 @@ impl RoleInterface for MockDb {
Ok(roles_list)
}
+
+ #[instrument(skip_all)]
+ async fn generic_list_roles_by_entity_type(
+ &self,
+ entity_type: storage::ListRolesByEntityPayload,
+ is_lineage_data_required: bool,
+ limit: Option<u32>,
+ ) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
+ let roles = self.roles.lock().await;
+ let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX);
+ let roles_list: Vec<_> = roles
+ .iter()
+ .filter(|role| match &entity_type {
+ storage::ListRolesByEntityPayload::Organization(org_id) => {
+ let entity_in_vec = if is_lineage_data_required {
+ vec![
+ EntityType::Organization,
+ EntityType::Merchant,
+ EntityType::Profile,
+ ]
+ } else {
+ vec![EntityType::Organization]
+ };
+
+ let matches_scope = role.scope == RoleScope::Organization
+ || role.scope == RoleScope::Merchant
+ || role.scope == RoleScope::Profile;
+
+ role.org_id == *org_id
+ && (matches_scope)
+ && entity_in_vec.contains(&role.entity_type)
+ }
+ storage::ListRolesByEntityPayload::Merchant(org_id, merchant_id) => {
+ let entity_in_vec = if is_lineage_data_required {
+ vec![EntityType::Merchant, EntityType::Profile]
+ } else {
+ vec![EntityType::Merchant]
+ };
+
+ let matches_merchant =
+ role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant;
+ let matches_profile =
+ role.merchant_id == *merchant_id && role.scope == RoleScope::Profile;
+
+ role.org_id == *org_id
+ && (role.scope == RoleScope::Organization
+ || matches_merchant
+ || matches_profile)
+ && entity_in_vec.contains(&role.entity_type)
+ }
+ storage::ListRolesByEntityPayload::Profile(org_id, merchant_id, profile_id) => {
+ let entity_in_vec = [EntityType::Profile];
+
+ let matches_merchant =
+ role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant;
+
+ let matches_profile = role.merchant_id == *merchant_id
+ && role
+ .profile_id
+ .as_ref()
+ .map(|profile_id_from_role| {
+ profile_id_from_role == profile_id
+ && role.scope == RoleScope::Profile
+ })
+ .unwrap_or(true);
+
+ role.org_id == *org_id
+ && (role.scope == RoleScope::Organization
+ || matches_merchant
+ || matches_profile)
+ && entity_in_vec.contains(&role.entity_type)
+ }
+ })
+ .take(limit_usize)
+ .cloned()
+ .collect();
+
+ Ok(roles_list)
+ }
}
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 9910cef3950..79b9be6b803 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -88,7 +88,7 @@ pub async fn create_role(
json_payload.into_inner(),
role_core::create_role,
&auth::JWTAuth {
- permission: Permission::MerchantUserWrite,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql b/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql
new file mode 100644
index 00000000000..d611be2c3da
--- /dev/null
+++ b/migrations/2024-10-17-073555_add-profile-id-to-roles/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE roles DROP COLUMN IF EXISTS profile_id;
\ No newline at end of file
diff --git a/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql b/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql
new file mode 100644
index 00000000000..b3873266fec
--- /dev/null
+++ b/migrations/2024-10-17-073555_add-profile-id-to-roles/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE roles ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64);
\ No newline at end of file
diff --git a/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql
new file mode 100644
index 00000000000..c7c9cbeb401
--- /dev/null
+++ b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+SELECT 1;
\ No newline at end of file
diff --git a/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql
new file mode 100644
index 00000000000..6fd9b07fd50
--- /dev/null
+++ b/migrations/2024-10-17-123943_add-profile-enum-in-role-scope/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TYPE "RoleScope"
+ADD VALUE IF NOT EXISTS 'profile';
\ No newline at end of file
|
2024-10-21T12:06:08Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Earlier we only had access to create Merchant level custom role at Org and Merchant scope . But after this user can be able to create custom role at Profile level at Organization , Merchant and Profile scope
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes [6488](https://github.com/juspay/hyperswitch/issues/6488)
## How did you test 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 Custom role at profile level**
```sh
curl --location 'http://localhost:8080/user/role' \
--header 'authorization: Bearer user JWT Token' \
--data '{
"role_scope": "organization",
"groups": [
"operations_view",
"operations_manage",
"connectors_view"
],
"role_name": "org-scope-profile-role-org-user",
"entity_type":"profile"
}'
```
Response :
```json
{
"role_id": "some_role_id",
"groups": [
"operations_view",
"operations_manage",
"connectors_view"
],
"role_name": "org-scope-profile-role-org-user",
"role_scope": "organization",
"entity_type": "profile"
}
```
To create a profile level custom role , the following scenarios the operation should be allowed
| Role scope | Org level user | merchant level user | Profile level user |
|-------------|----------------|---------------------|--------------------|
| Org | true | false | false |
| Merchant | true | true | false |
| Profile | true | true | true |
**Create Custom role at merchant level**
```sh
curl --location 'http://localhost:8080/user/role' \
--header 'authorization: Bearer user JWT Token' \
--data '{
"role_scope": "organization",
"groups": [
"operations_view",
"operations_manage",
"connectors_view"
],
"role_name": "org-scope-merchnant-role-org-user",
"entity_type":"merchant"
}'
```
Response :
```json
{
"role_id": "some_role_id",
"groups": [
"operations_view",
"operations_manage",
"connectors_view"
],
"role_name": "org-scope-merchnant-role-org-user",
"role_scope": "organization",
"entity_type": "merchant"
}
```
To create a merchant level custom role , the following scenarios the operation should be allowed
| Role scope | Org level user | merchant level user | Profile level user |
|-------------|----------------|---------------------|--------------------|
| Org | true | false | false |
| Merchant | true | true | false |
| Profile | false | false | false |
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
adc5262f130e25e9d711915ea9ad587bcbd0118f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6484
|
Bug: Refactor: interpolate success based routing params with their specific values
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 47d75b2e835..389af3dab7b 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -615,8 +615,11 @@ impl Default for SuccessBasedRoutingConfig {
pub enum SuccessBasedRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
- Currency,
AuthenticationType,
+ Currency,
+ Country,
+ CardNetwork,
+ CardBin,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
index 5afd3024551..e7b229a8070 100644
--- a/crates/external_services/src/grpc_client.rs
+++ b/crates/external_services/src/grpc_client.rs
@@ -5,7 +5,6 @@ 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
@@ -38,8 +37,6 @@ impl GrpcClientSettings {
.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
index 343dd80e951..0546d05ba7c 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -9,6 +9,7 @@ use error_stack::ResultExt;
use http_body_util::combinators::UnsyncBoxBody;
use hyper::body::Bytes;
use hyper_util::client::legacy::connect::HttpConnector;
+use router_env::logger;
use serde;
use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
@@ -80,6 +81,7 @@ impl DynamicRoutingClientConfig {
let success_rate_client = match self {
Self::Enabled { host, port } => {
let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?;
+ logger::info!("Connection established with dynamic routing gRPC Server");
Some(SuccessRateCalculatorClient::with_origin(client, uri))
}
Self::Disabled => None,
@@ -98,6 +100,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
label_input: Vec<RoutableConnectorChoice>,
) -> DynamicRoutingResult<CalSuccessRateResponse>;
/// To update the success rate with the given label
@@ -105,6 +108,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
response: Vec<RoutableConnectorChoiceWithStatus>,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>;
}
@@ -115,24 +119,9 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
label_input: Vec<RoutableConnectorChoice>,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
- let params = success_rate_based_config
- .params
- .map(|vec| {
- vec.into_iter().fold(String::new(), |mut acc_str, params| {
- if !acc_str.is_empty() {
- acc_str.push(':')
- }
- acc_str.push_str(params.to_string().as_str());
- acc_str
- })
- })
- .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())
@@ -167,6 +156,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
+ params: String,
label_input: Vec<RoutableConnectorChoiceWithStatus>,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
let config = success_rate_based_config
@@ -182,22 +172,6 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
})
.collect();
- let params = success_rate_based_config
- .params
- .map(|vec| {
- vec.into_iter().fold(String::new(), |mut acc_str, params| {
- if !acc_str.is_empty() {
- acc_str.push(':')
- }
- acc_str.push_str(params.to_string().as_str());
- acc_str
- })
- })
- .get_required_value("params")
- .change_context(DynamicRoutingError::MissingRequiredField {
- field: "params".to_string(),
- })?;
-
let request = tonic::Request::new(UpdateSuccessRateWindowRequest {
id,
params,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d095b471e2d..96321d09794 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -330,6 +330,8 @@ pub enum RoutingError {
MetadataParsingError,
#[error("Unable to retrieve success based routing config")]
SuccessBasedRoutingConfigError,
+ #[error("Params not found in success based routing config")]
+ SuccessBasedRoutingParamsNotFoundError,
#[error("Unable to calculate success based routing config from dynamic routing service")]
SuccessRateCalculationError,
#[error("Success rate client from dynamic routing gRPC service not initialized")]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 5d75001b118..4ad00df9c24 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -72,6 +72,8 @@ use super::{
#[cfg(feature = "frm")]
use crate::core::fraud_check as frm_core;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use crate::core::routing::helpers as routing_helpers;
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::types::api::convert_connector_data_to_routable_connectors;
use crate::{
configs::settings::{ApplePayPreDecryptFlow, PaymentMethodTypeTokenFilter},
@@ -5580,10 +5582,46 @@ where
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
let connectors = {
if business_profile.dynamic_routing_algorithm.is_some() {
- routing::perform_success_based_routing(state, connectors.clone(), business_profile)
- .await
- .map_err(|e| logger::error!(success_rate_routing_error=?e))
- .unwrap_or(connectors)
+ let success_based_routing_config_params_interpolator =
+ routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
+ payment_data.get_payment_attempt().payment_method,
+ payment_data.get_payment_attempt().payment_method_type,
+ payment_data.get_payment_attempt().authentication_type,
+ payment_data.get_payment_attempt().currency,
+ payment_data
+ .get_billing_address()
+ .and_then(|address| address.address)
+ .and_then(|address| address.country),
+ payment_data
+ .get_payment_attempt()
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
+ payment_data
+ .get_payment_attempt()
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_isin"))
+ .and_then(|card_isin| card_isin.as_str())
+ .map(|card_isin| card_isin.to_string()),
+ );
+ routing::perform_success_based_routing(
+ state,
+ connectors.clone(),
+ business_profile,
+ success_based_routing_config_params_interpolator,
+ )
+ .await
+ .map_err(|e| logger::error!(success_rate_routing_error=?e))
+ .unwrap_or(connectors)
} else {
connectors
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 0234b97032c..f0381dbf822 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -21,7 +21,7 @@ use tracing_futures::Instrument;
use super::{Operation, OperationSessionSetters, PostUpdateTracker};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use crate::core::routing::helpers::push_metrics_for_success_based_routing;
+use crate::core::routing::helpers as routing_helpers;
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
@@ -1968,13 +1968,44 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let state = state.clone();
let business_profile = business_profile.clone();
let payment_attempt = payment_attempt.clone();
+ let success_based_routing_config_params_interpolator =
+ routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new(
+ payment_attempt.payment_method,
+ payment_attempt.payment_method_type,
+ payment_attempt.authentication_type,
+ payment_attempt.currency,
+ payment_data
+ .address
+ .get_payment_billing()
+ .and_then(|address| address.clone().address)
+ .and_then(|address| address.country),
+ payment_attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_network"))
+ .and_then(|network| network.as_str())
+ .map(|network| network.to_string()),
+ payment_attempt
+ .payment_method_data
+ .as_ref()
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card"))
+ .and_then(|data| data.as_object())
+ .and_then(|card| card.get("card_isin"))
+ .and_then(|card_isin| card_isin.as_str())
+ .map(|card_isin| card_isin.to_string()),
+ );
tokio::spawn(
async move {
- push_metrics_for_success_based_routing(
+ routing_helpers::push_metrics_with_update_window_for_success_based_routing(
&state,
&payment_attempt,
routable_connectors,
&business_profile,
+ success_based_routing_config_params_interpolator,
)
.await
.map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
@@ -1984,6 +2015,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
);
}
}
+
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
router_data.payment_method_status.and_then(|status| {
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 40721e9b4c3..28321529ef2 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -1240,6 +1240,7 @@ pub async fn perform_success_based_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
business_profile: &domain::Profile,
+ success_based_routing_config_params_interpolator: routing::helpers::SuccessBasedRoutingConfigParamsInterpolator,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef =
business_profile
@@ -1293,6 +1294,14 @@ pub async fn perform_success_based_routing(
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
.attach_printable("unable to fetch success_rate based dynamic routing configs")?;
+ let success_based_routing_config_params = success_based_routing_config_params_interpolator
+ .get_string_val(
+ success_based_routing_configs
+ .params
+ .as_ref()
+ .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?,
+ );
+
let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(
&state.tenant.redis_key_prefix,
business_profile.get_id().get_string_repr(),
@@ -1302,6 +1311,7 @@ pub async fn perform_success_based_routing(
.calculate_success_rate(
tenant_business_profile_id,
success_based_routing_configs,
+ success_based_routing_config_params,
routable_connectors,
)
.await
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 31cd4234714..0250d00d1bb 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -640,11 +640,12 @@ pub async fn fetch_success_based_routing_configs(
/// metrics for success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
-pub async fn push_metrics_for_success_based_routing(
+pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
business_profile: &domain::Profile,
+ success_based_routing_config_params_interpolator: SuccessBasedRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
let success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef =
business_profile
@@ -697,10 +698,20 @@ pub async fn push_metrics_for_success_based_routing(
business_profile.get_id().get_string_repr(),
);
+ let success_based_routing_config_params = success_based_routing_config_params_interpolator
+ .get_string_val(
+ success_based_routing_configs
+ .params
+ .as_ref()
+ .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ );
+
let success_based_connectors = client
.calculate_success_rate(
tenant_business_profile_id.clone(),
success_based_routing_configs.clone(),
+ success_based_routing_config_params.clone(),
routable_connectors.clone(),
)
.await
@@ -725,9 +736,10 @@ pub async fn push_metrics_for_success_based_routing(
let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service",
- )?;
+ .attach_printable(format!(
+ "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
+ first_success_based_connector_label
+ ))?;
let outcome = get_success_based_metrics_outcome_for_payment(
&payment_status_attribute,
@@ -802,6 +814,7 @@ pub async fn push_metrics_for_success_based_routing(
.update_success_rate(
tenant_business_profile_id,
success_based_routing_configs,
+ success_based_routing_config_params,
vec![routing_types::RoutableConnectorChoiceWithStatus::new(
routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
@@ -956,3 +969,76 @@ pub async fn default_success_based_routing_setup(
);
Ok(ApplicationResponse::Json(new_record))
}
+
+pub struct SuccessBasedRoutingConfigParamsInterpolator {
+ pub payment_method: Option<common_enums::PaymentMethod>,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub authentication_type: Option<common_enums::AuthenticationType>,
+ pub currency: Option<common_enums::Currency>,
+ pub country: Option<common_enums::CountryAlpha2>,
+ pub card_network: Option<String>,
+ pub card_bin: Option<String>,
+}
+
+impl SuccessBasedRoutingConfigParamsInterpolator {
+ pub fn new(
+ payment_method: Option<common_enums::PaymentMethod>,
+ payment_method_type: Option<common_enums::PaymentMethodType>,
+ authentication_type: Option<common_enums::AuthenticationType>,
+ currency: Option<common_enums::Currency>,
+ country: Option<common_enums::CountryAlpha2>,
+ card_network: Option<String>,
+ card_bin: Option<String>,
+ ) -> Self {
+ Self {
+ payment_method,
+ payment_method_type,
+ authentication_type,
+ currency,
+ country,
+ card_network,
+ card_bin,
+ }
+ }
+
+ pub fn get_string_val(
+ &self,
+ params: &Vec<routing_types::SuccessBasedRoutingConfigParams>,
+ ) -> String {
+ let mut parts: Vec<String> = Vec::new();
+ for param in params {
+ let val = match param {
+ routing_types::SuccessBasedRoutingConfigParams::PaymentMethod => self
+ .payment_method
+ .as_ref()
+ .map_or(String::new(), |pm| pm.to_string()),
+ routing_types::SuccessBasedRoutingConfigParams::PaymentMethodType => self
+ .payment_method_type
+ .as_ref()
+ .map_or(String::new(), |pmt| pmt.to_string()),
+ routing_types::SuccessBasedRoutingConfigParams::AuthenticationType => self
+ .authentication_type
+ .as_ref()
+ .map_or(String::new(), |at| at.to_string()),
+ routing_types::SuccessBasedRoutingConfigParams::Currency => self
+ .currency
+ .as_ref()
+ .map_or(String::new(), |cur| cur.to_string()),
+ routing_types::SuccessBasedRoutingConfigParams::Country => self
+ .country
+ .as_ref()
+ .map_or(String::new(), |cn| cn.to_string()),
+ routing_types::SuccessBasedRoutingConfigParams::CardNetwork => {
+ self.card_network.clone().unwrap_or_default()
+ }
+ routing_types::SuccessBasedRoutingConfigParams::CardBin => {
+ self.card_bin.clone().unwrap_or_default()
+ }
+ };
+ if !val.is_empty() {
+ parts.push(val);
+ }
+ }
+ parts.join(":")
+ }
+}
|
2024-10-28T08:12:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will interpolate the success_based_routing config params with the specific payment's values:
So for now the redis key was something like PaymentMethod:Currency
After this change it will be something like Card:USD
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 is tested locally can't be tested on sbx or integ as it requires access for redis.
<img width="1292" alt="Screenshot 2024-11-07 at 5 14 06 PM" src="https://github.com/user-attachments/assets/b5a096ae-3ab7-4e94-9aa0-502b7ab94417">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
90d9ffc1d2e13b83931762b05632056520eea07f
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add 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">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
43d87913ab3d177a6d193b3e475c96609cc09a28
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6461
|
Bug: fix(analytics): add dynamic limit by clause in failure reasons metric query
Currently, the `limit by` clause in query_builder of `failure_reasons` metric has only `connector` hardcoded.
Should change this behaviour to enable dynamic addition of `group by` fields to the `limit by `clause as well.
|
diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
index 70ae64e0115..bcbce0502d2 100644
--- a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs
@@ -148,17 +148,20 @@ where
.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()?;
- }
+ let filtered_dimensions: Vec<&PaymentDimensions> = dimensions
+ .iter()
+ .filter(|&&dim| dim != PaymentDimensions::ErrorReason)
+ .collect();
+
+ for dim in &filtered_dimensions {
+ 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])
+ .set_limit_by(5, &filtered_dimensions)
.attach_printable("Error adding limit clause")
.switch()?;
|
2024-10-29T10:33:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Currently, the `limit by` clause in query_builder of `failure_reasons` metric has only `connector` hardcoded.
- Changed this behaviour to enable dynamic addition of `group` by fields to the `limit by` clause as well.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Prevent errors when connector is not passed as a group by and also provide dynamic combination of error_reason with other filters like connector, payment_method, payment_method_type, etc.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Hit the curl:
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMDI2NjUwMCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.p6u5u3k6-80GBh7_0Kri9VmIvZc3h2bx48UEQraeLA8' \
--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-11T18:30:00Z",
"endTime": "2024-10-30T09:22:00Z"
},
"groupByNames": [
"connector", "payment_method", "payment_method_type", "error_reason"
],
"filters": {
"merchant_id": ["merchant_1726046328"]
},
"source": "BATCH",
"metrics": [
"failure_reasons"
],
"delta": true
}
]'
```
Sample response:
```bash
{
"queryData": [
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 0,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"failure_reason_count": 1,
"failure_reason_count_without_smart_retries": 1,
"currency": null,
"status": null,
"connector": "stripe_test",
"authentication_type": null,
"payment_method": "card",
"payment_method_type": "credit",
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": "TEST FAILURE - 1",
"time_range": {
"start_time": "2024-09-11T18:30:00.000Z",
"end_time": "2024-10-30T09:22:00.000Z"
},
"time_bucket": "2024-09-11 18:30:00"
}
],
"metaData": [
{
"total_payment_processed_amount": 0,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0,
"total_failure_reasons_count": 1,
"total_failure_reasons_count_without_smart_retries": 1
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
55a81eb4692979036d0bfd43e445d3e1db6601e7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6489
|
Bug: [FEATURE] Add payments update-intent API for v2
Add payments `update-intent` API for v2
|
diff --git a/api-reference-v2/api-reference/payments/payments--update-intent.mdx b/api-reference-v2/api-reference/payments/payments--update-intent.mdx
new file mode 100644
index 00000000000..3ef58f4db72
--- /dev/null
+++ b/api-reference-v2/api-reference/payments/payments--update-intent.mdx
@@ -0,0 +1,3 @@
+---
+openapi: put /v2/payments/{id}/update-intent
+---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index aed89492443..4212b2dbd21 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -40,6 +40,7 @@
"pages": [
"api-reference/payments/payments--create-intent",
"api-reference/payments/payments--get-intent",
+ "api-reference/payments/payments--update-intent",
"api-reference/payments/payments--session-token",
"api-reference/payments/payments--confirm-intent",
"api-reference/payments/payments--get"
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 778e89ab30b..64949c3812b 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -1911,6 +1911,79 @@
]
}
},
+ "/v2/payments/{id}/update-intent": {
+ "put": {
+ "tags": [
+ "Payments"
+ ],
+ "summary": "Payments - Update Intent",
+ "description": "**Update a payment intent object**\n\nYou will require the 'API - Key' from the Hyperswitch dashboard to make the call.",
+ "operationId": "Update a Payment Intent",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Intent",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "Profile ID associated to the payment intent",
+ "required": true,
+ "schema": {
+ "type": "string"
+ },
+ "example": {
+ "X-Profile-Id": "pro_abcdefghijklmnop"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentsUpdateIntentRequest"
+ },
+ "examples": {
+ "Update a payment intent with minimal fields": {
+ "value": {
+ "amount_details": {
+ "currency": "USD",
+ "order_amount": 6540
+ }
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payment Intent Updated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentsIntentResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payment Intent Not Found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/payments/{id}/confirm-intent": {
"post": {
"tags": [
@@ -3026,6 +3099,75 @@
}
}
},
+ "AmountDetailsUpdate": {
+ "type": "object",
+ "properties": {
+ "order_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 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
+ },
+ "currency": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Currency"
+ }
+ ],
+ "nullable": true
+ },
+ "shipping_cost": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "skip_external_tax_calculation": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/TaxCalculationOverride"
+ }
+ ],
+ "nullable": true
+ },
+ "skip_surcharge_calculation": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/SurchargeCalculationOverride"
+ }
+ ],
+ "nullable": true
+ },
+ "surcharge_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "tax_on_surcharge": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"AmountFilter": {
"type": "object",
"properties": {
@@ -15898,6 +16040,176 @@
}
}
},
+ "PaymentsUpdateIntentRequest": {
+ "type": "object",
+ "properties": {
+ "amount_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AmountDetailsUpdate"
+ }
+ ],
+ "nullable": true
+ },
+ "routing_algorithm_id": {
+ "type": "string",
+ "description": "The routing algorithm id to be used for the payment",
+ "nullable": true
+ },
+ "capture_method": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CaptureMethod"
+ }
+ ],
+ "nullable": true
+ },
+ "authentication_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AuthenticationType"
+ }
+ ],
+ "default": "no_three_ds",
+ "nullable": true
+ },
+ "billing": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "shipping": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "customer_present": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment"
+ }
+ ],
+ "nullable": true
+ },
+ "description": {
+ "type": "string",
+ "description": "A description for the payment",
+ "example": "It's my first payment request",
+ "nullable": true
+ },
+ "return_url": {
+ "type": "string",
+ "description": "The URL to which you want the user to be redirected after the completion of the payment operation",
+ "example": "https://hyperswitch.io",
+ "nullable": true
+ },
+ "setup_future_usage": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FutureUsage"
+ }
+ ],
+ "nullable": true
+ },
+ "apply_mit_exemption": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MitExemptionRequest"
+ }
+ ],
+ "nullable": true
+ },
+ "statement_descriptor": {
+ "type": "string",
+ "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.",
+ "example": "Hyperswitch Router",
+ "nullable": true,
+ "maxLength": 22
+ },
+ "order_details": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/OrderDetailsWithAmount"
+ },
+ "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount",
+ "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]",
+ "nullable": true
+ },
+ "allowed_payment_method_types": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ },
+ "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent",
+ "nullable": true
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments",
+ "nullable": true
+ },
+ "connector_metadata": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorMetadata"
+ }
+ ],
+ "nullable": true
+ },
+ "feature_metadata": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FeatureMetadata"
+ }
+ ],
+ "nullable": true
+ },
+ "payment_link_config": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ }
+ ],
+ "nullable": true
+ },
+ "request_incremental_authorization": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RequestIncrementalAuthorization"
+ }
+ ],
+ "nullable": true
+ },
+ "session_expiry": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config\n(900) for 15 mins",
+ "example": 900,
+ "nullable": true,
+ "minimum": 0
+ },
+ "frm_metadata": {
+ "type": "object",
+ "description": "Additional data related to some frm(Fraud Risk Management) connectors",
+ "nullable": true
+ },
+ "request_external_three_ds_authentication": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/External3dsAuthenticationRequest"
+ }
+ ],
+ "nullable": true
+ }
+ },
+ "additionalProperties": false
+ },
"PayoutActionRequest": {
"type": "object"
},
@@ -17189,10 +17501,10 @@
},
"PresenceOfCustomerDuringPayment": {
"type": "string",
- "description": "Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment.",
+ "description": "Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.",
"enum": [
- "Present",
- "Absent"
+ "present",
+ "absent"
]
},
"PrimaryBusinessDetails": {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 603c0f76934..6a7f7148bd3 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -156,8 +156,8 @@ pub struct PaymentsCreateIntentRequest {
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
- /// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment.
- #[schema(example = true, value_type = Option<PresenceOfCustomerDuringPayment>)]
+ /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
+ #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)]
pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
/// A description for the payment
@@ -297,6 +297,99 @@ pub struct PaymentsGetIntentRequest {
pub id: id_type::GlobalPaymentId,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[cfg(feature = "v2")]
+pub struct PaymentsUpdateIntentRequest {
+ pub amount_details: Option<AmountDetailsUpdate>,
+
+ /// The routing algorithm id to be used for the payment
+ #[schema(value_type = Option<String>)]
+ pub routing_algorithm_id: Option<id_type::RoutingId>,
+
+ #[schema(value_type = Option<CaptureMethod>, example = "automatic")]
+ pub capture_method: Option<api_enums::CaptureMethod>,
+
+ #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")]
+ pub authentication_type: Option<api_enums::AuthenticationType>,
+
+ /// The billing details of the payment. This address will be used for invoicing.
+ pub billing: Option<Address>,
+
+ /// The shipping address for the payment
+ pub shipping: Option<Address>,
+
+ /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
+ #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)]
+ pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
+
+ /// A description for the payment
+ #[schema(example = "It's my first payment request", value_type = Option<String>)]
+ pub description: Option<common_utils::types::Description>,
+
+ /// The URL to which you want the user to be redirected after the completion of the payment operation
+ #[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
+ pub return_url: Option<common_utils::types::Url>,
+
+ #[schema(value_type = Option<FutureUsage>, example = "off_session")]
+ pub setup_future_usage: Option<api_enums::FutureUsage>,
+
+ /// Apply MIT exemption for a payment
+ #[schema(value_type = Option<MitExemptionRequest>)]
+ pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>,
+
+ /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
+ #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)]
+ pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
+
+ /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
+ #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
+ "product_name": "Apple iPhone 16",
+ "quantity": 1,
+ "amount" : 69000
+ "product_img_link" : "https://dummy-img-link.com"
+ }]"#)]
+ pub order_details: Option<Vec<OrderDetailsWithAmount>>,
+
+ /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
+ #[schema(value_type = Option<Vec<PaymentMethodType>>)]
+ pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
+
+ /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments
+ #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below.
+ #[schema(value_type = Option<ConnectorMetadata>)]
+ pub connector_metadata: Option<pii::SecretSerdeValue>,
+
+ /// Additional data that might be required by hyperswitch based on the requested features by the merchants.
+ #[schema(value_type = Option<FeatureMetadata>)]
+ pub feature_metadata: Option<FeatureMetadata>,
+
+ /// Configure a custom payment link for the particular payment
+ #[schema(value_type = Option<PaymentLinkConfigRequest>)]
+ pub payment_link_config: Option<admin::PaymentLinkConfigRequest>,
+
+ /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.
+ #[schema(value_type = Option<RequestIncrementalAuthorization>)]
+ pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>,
+
+ /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config
+ ///(900) for 15 mins
+ #[schema(value_type = Option<u32>, example = 900)]
+ pub session_expiry: Option<u32>,
+
+ /// Additional data related to some frm(Fraud Risk Management) connectors
+ #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
+ pub frm_metadata: Option<pii::SecretSerdeValue>,
+
+ /// Whether to perform external authentication (if applicable)
+ #[schema(value_type = Option<External3dsAuthenticationRequest>)]
+ pub request_external_three_ds_authentication:
+ Option<common_enums::External3dsAuthenticationRequest>,
+}
+
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
@@ -352,8 +445,8 @@ pub struct PaymentsIntentResponse {
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
- /// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment.
- #[schema(example = true, value_type = PresenceOfCustomerDuringPayment)]
+ /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
+ #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)]
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
/// A description for the payment
@@ -453,6 +546,32 @@ pub struct AmountDetails {
tax_on_surcharge: Option<MinorUnit>,
}
+#[cfg(feature = "v2")]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct AmountDetailsUpdate {
+ /// 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")]
+ order_amount: Option<Amount>,
+ /// The currency of the order
+ #[schema(example = "USD", value_type = Option<Currency>)]
+ currency: Option<common_enums::Currency>,
+ /// The shipping cost of the order. This has to be collected from the merchant
+ shipping_cost: Option<MinorUnit>,
+ /// Tax amount related to the order. This will be calculated by the external tax provider
+ order_tax_amount: Option<MinorUnit>,
+ /// The action to whether calculate tax by calling external tax provider or not
+ #[schema(value_type = Option<TaxCalculationOverride>)]
+ skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>,
+ /// The action to whether calculate surcharge or not
+ #[schema(value_type = Option<SurchargeCalculationOverride>)]
+ skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>,
+ /// The surcharge amount to be added to the order, collected from the merchant
+ surcharge_amount: Option<MinorUnit>,
+ /// tax on surcharge amount
+ tax_on_surcharge: Option<MinorUnit>,
+}
+
#[cfg(feature = "v2")]
pub struct AmountDetailsSetter {
pub order_amount: Amount,
@@ -552,10 +671,10 @@ impl AmountDetails {
self.order_tax_amount
}
pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride {
- self.skip_external_tax_calculation.clone()
+ self.skip_external_tax_calculation
}
pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride {
- self.skip_surcharge_calculation.clone()
+ self.skip_surcharge_calculation
}
pub fn surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
@@ -565,6 +684,33 @@ impl AmountDetails {
}
}
+#[cfg(feature = "v2")]
+impl AmountDetailsUpdate {
+ pub fn order_amount(&self) -> Option<Amount> {
+ self.order_amount
+ }
+ pub fn currency(&self) -> Option<common_enums::Currency> {
+ self.currency
+ }
+ pub fn shipping_cost(&self) -> Option<MinorUnit> {
+ self.shipping_cost
+ }
+ pub fn order_tax_amount(&self) -> Option<MinorUnit> {
+ self.order_tax_amount
+ }
+ pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> {
+ self.skip_external_tax_calculation
+ }
+ pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> {
+ self.skip_surcharge_calculation
+ }
+ pub fn surcharge_amount(&self) -> Option<MinorUnit> {
+ self.surcharge_amount
+ }
+ pub fn tax_on_surcharge(&self) -> Option<MinorUnit> {
+ self.tax_on_surcharge
+ }
+}
#[cfg(feature = "v1")]
#[derive(
Default,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index c3c876b22aa..6c38172e540 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3332,8 +3332,9 @@ pub enum MitExemptionRequest {
Skip,
}
-/// Set to true to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be false when merchant's doing merchant initiated payments and customer is not present while doing the payment.
+/// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)]
+#[serde(rename_all = "snake_case")]
pub enum PresenceOfCustomerDuringPayment {
/// Customer is present during the payment. This is the default value
#[default]
@@ -3352,7 +3353,9 @@ impl From<ConnectorType> for TransactionType {
}
}
-#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)]
+#[derive(
+ Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
+)]
#[serde(rename_all = "snake_case")]
pub enum TaxCalculationOverride {
/// Skip calling the external tax provider
@@ -3362,7 +3365,27 @@ pub enum TaxCalculationOverride {
Calculate,
}
-#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)]
+impl From<Option<bool>> for TaxCalculationOverride {
+ fn from(value: Option<bool>) -> Self {
+ match value {
+ Some(true) => Self::Calculate,
+ _ => Self::Skip,
+ }
+ }
+}
+
+impl TaxCalculationOverride {
+ pub fn as_bool(self) -> bool {
+ match self {
+ Self::Skip => false,
+ Self::Calculate => true,
+ }
+ }
+}
+
+#[derive(
+ Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema,
+)]
#[serde(rename_all = "snake_case")]
pub enum SurchargeCalculationOverride {
/// Skip calculating surcharge
@@ -3372,6 +3395,24 @@ pub enum SurchargeCalculationOverride {
Calculate,
}
+impl From<Option<bool>> for SurchargeCalculationOverride {
+ fn from(value: Option<bool>) -> Self {
+ match value {
+ Some(true) => Self::Calculate,
+ _ => Self::Skip,
+ }
+ }
+}
+
+impl SurchargeCalculationOverride {
+ pub fn as_bool(self) -> bool {
+ match self {
+ Self::Skip => false,
+ Self::Calculate => true,
+ }
+ }
+}
+
/// Connector Mandate Status
#[derive(
Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display,
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 7c5c3a8de17..80159271292 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -3,6 +3,8 @@ use serde::{Deserialize, Serialize};
#[cfg(feature = "v2")]
use crate::payment_attempt::PaymentAttemptUpdateInternal;
+#[cfg(feature = "v1")]
+use crate::payment_intent::PaymentIntentUpdate;
#[cfg(feature = "v2")]
use crate::payment_intent::PaymentIntentUpdateInternal;
use crate::{
@@ -10,7 +12,7 @@ use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
- payment_intent::{PaymentIntentNew, PaymentIntentUpdate},
+ payment_intent::PaymentIntentNew,
payout_attempt::{PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate},
payouts::{Payouts, PayoutsNew, PayoutsUpdate},
refund::{Refund, RefundNew, RefundUpdate},
@@ -115,11 +117,9 @@ impl DBOperation {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
#[cfg(feature = "v2")]
- Updateable::PaymentIntentUpdate(a) => DBResult::PaymentIntent(Box::new(
- a.orig
- .update(conn, PaymentIntentUpdateInternal::from(a.update_data))
- .await?,
- )),
+ Updateable::PaymentIntentUpdate(a) => {
+ DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
+ }
#[cfg(feature = "v1")]
Updateable::PaymentAttemptUpdate(a) => DBResult::PaymentAttempt(Box::new(
a.orig.update_with_attempt_id(conn, a.update_data).await?,
@@ -247,13 +247,20 @@ pub struct AddressUpdateMems {
pub orig: Address,
pub update_data: AddressUpdateInternal,
}
-
+#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
pub update_data: PaymentIntentUpdate,
}
+#[cfg(feature = "v2")]
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PaymentIntentUpdateMems {
+ pub orig: PaymentIntent,
+ pub update_data: PaymentIntentUpdateInternal,
+}
+
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 9f0bf17230d..b29da50d0a7 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -140,7 +140,8 @@ pub struct PaymentIntent {
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq)]
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)]
+#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct PaymentLinkConfigRequestForPayments {
/// custom theme for the payment link
pub theme: Option<String>,
@@ -359,22 +360,6 @@ pub struct PaymentIntentNew {
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
}
-#[cfg(feature = "v2")]
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub enum PaymentIntentUpdate {
- /// Update the payment intent details on payment intent confirmation, before calling the connector
- ConfirmIntent {
- status: storage_enums::IntentStatus,
- active_attempt_id: common_utils::id_type::GlobalAttemptId,
- updated_by: String,
- },
- /// Update the payment intent details on payment intent confirmation, after calling the connector
- ConfirmIntentPostUpdate {
- status: storage_enums::IntentStatus,
- updated_by: String,
- },
-}
-
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaymentIntentUpdate {
@@ -516,34 +501,42 @@ pub struct PaymentIntentUpdateFields {
// TODO: uncomment fields as necessary
#[cfg(feature = "v2")]
-#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
+#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentUpdateInternal {
- // pub amount: Option<MinorUnit>,
- // pub currency: Option<storage_enums::Currency>,
pub status: Option<storage_enums::IntentStatus>,
- // pub amount_captured: Option<MinorUnit>,
- // pub customer_id: Option<common_utils::id_type::CustomerId>,
- // pub return_url: Option<>,
- // pub setup_future_usage: Option<storage_enums::FutureUsage>,
- // pub metadata: Option<pii::SecretSerdeValue>,
- pub modified_at: PrimitiveDateTime,
pub active_attempt_id: Option<common_utils::id_type::GlobalAttemptId>,
- // pub description: Option<String>,
- // pub statement_descriptor: Option<String>,
- // #[diesel(deserialize_as = super::OptionalDieselArray<pii::SecretSerdeValue>)]
- // pub order_details: Option<Vec<pii::SecretSerdeValue>>,
- // pub attempt_count: Option<i16>,
+ pub modified_at: PrimitiveDateTime,
+ pub amount: Option<MinorUnit>,
+ pub currency: Option<storage_enums::Currency>,
+ pub shipping_cost: Option<MinorUnit>,
+ pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
+ pub surcharge_applicable: Option<bool>,
+ pub surcharge_amount: Option<MinorUnit>,
+ pub tax_on_surcharge: Option<MinorUnit>,
+ pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
+ pub capture_method: Option<common_enums::CaptureMethod>,
+ pub authentication_type: Option<common_enums::AuthenticationType>,
+ pub billing_address: Option<Encryption>,
+ pub shipping_address: Option<Encryption>,
+ pub customer_present: Option<bool>,
+ pub description: Option<common_utils::types::Description>,
+ pub return_url: Option<common_utils::types::Url>,
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub apply_mit_exemption: Option<bool>,
+ pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
+ pub order_details: Option<Vec<masking::Secret<OrderDetailsWithAmount>>>,
+ pub allowed_payment_method_types: Option<pii::SecretSerdeValue>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub connector_metadata: Option<pii::SecretSerdeValue>,
+ pub feature_metadata: Option<FeatureMetadata>,
+ pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>,
+ pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
+ pub session_expiry: Option<PrimitiveDateTime>,
+ pub frm_metadata: Option<pii::SecretSerdeValue>,
+ pub request_external_three_ds_authentication: Option<bool>,
pub updated_by: String,
- // pub surcharge_applicable: Option<bool>,
- // pub authorization_count: Option<i32>,
- // pub session_expiry: Option<PrimitiveDateTime>,
- // pub request_external_three_ds_authentication: Option<bool>,
- // pub frm_metadata: Option<pii::SecretSerdeValue>,
- // pub customer_details: Option<Encryption>,
- // pub billing_address: Option<Encryption>,
- // pub shipping_address: Option<Encryption>,
- // pub frm_merchant_decision: Option<String>,
}
#[cfg(feature = "v1")]
@@ -589,66 +582,6 @@ pub struct PaymentIntentUpdateInternal {
pub tax_details: Option<TaxDetails>,
}
-#[cfg(feature = "v2")]
-impl PaymentIntentUpdate {
- pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent {
- let PaymentIntentUpdateInternal {
- // amount,
- // currency,
- status,
- // amount_captured,
- // customer_id,
- // return_url,
- // setup_future_usage,
- // metadata,
- modified_at: _,
- active_attempt_id,
- // description,
- // statement_descriptor,
- // order_details,
- // attempt_count,
- // frm_merchant_decision,
- updated_by,
- // surcharge_applicable,
- // authorization_count,
- // session_expiry,
- // request_external_three_ds_authentication,
- // frm_metadata,
- // customer_details,
- // billing_address,
- // shipping_address,
- } = self.into();
- PaymentIntent {
- // amount: amount.unwrap_or(source.amount),
- // currency: currency.unwrap_or(source.currency),
- status: status.unwrap_or(source.status),
- // amount_captured: amount_captured.or(source.amount_captured),
- // customer_id: customer_id.or(source.customer_id),
- // return_url: return_url.or(source.return_url),
- // setup_future_usage: setup_future_usage.or(source.setup_future_usage),
- // metadata: metadata.or(source.metadata),
- modified_at: common_utils::date_time::now(),
- active_attempt_id: active_attempt_id.or(source.active_attempt_id),
- // description: description.or(source.description),
- // statement_descriptor: statement_descriptor.or(source.statement_descriptor),
- // order_details: order_details.or(source.order_details),
- // attempt_count: attempt_count.unwrap_or(source.attempt_count),
- // frm_merchant_decision: frm_merchant_decision.or(source.frm_merchant_decision),
- updated_by,
- // surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable),
- // authorization_count: authorization_count.or(source.authorization_count),
- // session_expiry: session_expiry.or(source.session_expiry),
- // request_external_three_ds_authentication: request_external_three_ds_authentication
- // .or(source.request_external_three_ds_authentication),
- // frm_metadata: frm_metadata.or(source.frm_metadata),
- // customer_details: customer_details.or(source.customer_details),
- // billing_address: billing_address.or(source.billing_address),
- // shipping_address: shipping_address.or(source.shipping_address),
- ..source
- }
- }
-}
-
#[cfg(feature = "v1")]
impl PaymentIntentUpdate {
pub fn apply_changeset(self, source: PaymentIntent) -> PaymentIntent {
@@ -739,30 +672,6 @@ impl PaymentIntentUpdate {
}
}
-#[cfg(feature = "v2")]
-impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
- fn from(payment_intent_update: PaymentIntentUpdate) -> Self {
- match payment_intent_update {
- PaymentIntentUpdate::ConfirmIntent {
- status,
- active_attempt_id,
- updated_by,
- } => Self {
- status: Some(status),
- active_attempt_id: Some(active_attempt_id),
- modified_at: common_utils::date_time::now(),
- updated_by,
- },
- PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {
- status: Some(status),
- active_attempt_id: None,
- modified_at: common_utils::date_time::now(),
- updated_by,
- },
- }
- }
-}
-
#[cfg(feature = "v1")]
impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
fn from(payment_intent_update: PaymentIntentUpdate) -> Self {
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index d94e921c120..31732e13286 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -302,12 +302,8 @@ impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
payment_method_type: None,
}
}),
- skip_external_tax_calculation: payments::TaxCalculationOverride::from(
- amount_details.skip_external_tax_calculation(),
- ),
- skip_surcharge_calculation: payments::SurchargeCalculationOverride::from(
- amount_details.skip_surcharge_calculation(),
- ),
+ skip_external_tax_calculation: amount_details.skip_external_tax_calculation(),
+ skip_surcharge_calculation: amount_details.skip_surcharge_calculation(),
surcharge_amount: amount_details.surcharge_amount(),
tax_on_surcharge: amount_details.tax_on_surcharge(),
// We will not receive this in the request. This will be populated after calling the connector / processor
@@ -315,23 +311,3 @@ impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
}
}
}
-
-#[cfg(feature = "v2")]
-impl From<common_enums::SurchargeCalculationOverride> for payments::SurchargeCalculationOverride {
- fn from(surcharge_calculation_override: common_enums::SurchargeCalculationOverride) -> Self {
- match surcharge_calculation_override {
- common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate,
- common_enums::SurchargeCalculationOverride::Skip => Self::Skip,
- }
- }
-}
-
-#[cfg(feature = "v2")]
-impl From<common_enums::TaxCalculationOverride> for payments::TaxCalculationOverride {
- fn from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self {
- match tax_calculation_override {
- common_enums::TaxCalculationOverride::Calculate => Self::Calculate,
- common_enums::TaxCalculationOverride::Skip => Self::Skip,
- }
- }
-}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 207668817e3..9e6477fa26b 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -17,6 +17,8 @@ use diesel_models::payment_intent::TaxDetails;
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use masking::Secret;
+#[cfg(feature = "v2")]
+use payment_intent::PaymentIntentUpdate;
use router_derive::ToEncryption;
use rustc_hash::FxHashMap;
use serde_json::Value;
@@ -155,44 +157,6 @@ impl PaymentIntent {
}
}
-#[cfg(feature = "v2")]
-#[derive(Clone, Debug, PartialEq, Copy, serde::Serialize)]
-pub enum TaxCalculationOverride {
- /// Skip calling the external tax provider
- Skip,
- /// Calculate tax by calling the external tax provider
- Calculate,
-}
-
-#[cfg(feature = "v2")]
-#[derive(Clone, Debug, PartialEq, Copy, serde::Serialize)]
-pub enum SurchargeCalculationOverride {
- /// Skip calculating surcharge
- Skip,
- /// Calculate surcharge
- Calculate,
-}
-
-#[cfg(feature = "v2")]
-impl From<Option<bool>> for TaxCalculationOverride {
- fn from(value: Option<bool>) -> Self {
- match value {
- Some(true) => Self::Calculate,
- _ => Self::Skip,
- }
- }
-}
-
-#[cfg(feature = "v2")]
-impl From<Option<bool>> for SurchargeCalculationOverride {
- fn from(value: Option<bool>) -> Self {
- match value {
- Some(true) => Self::Calculate,
- _ => Self::Skip,
- }
- }
-}
-
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct AmountDetails {
@@ -205,9 +169,9 @@ pub struct AmountDetails {
/// Tax details related to the order. This will be calculated by the external tax provider
pub tax_details: Option<TaxDetails>,
/// The action to whether calculate tax by calling external tax provider or not
- pub skip_external_tax_calculation: TaxCalculationOverride,
+ pub skip_external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
- pub skip_surcharge_calculation: SurchargeCalculationOverride,
+ pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
@@ -221,18 +185,12 @@ pub struct AmountDetails {
impl AmountDetails {
/// Get the action to whether calculate surcharge or not as a boolean value
fn get_surcharge_action_as_bool(&self) -> bool {
- match self.skip_surcharge_calculation {
- SurchargeCalculationOverride::Skip => false,
- SurchargeCalculationOverride::Calculate => true,
- }
+ self.skip_surcharge_calculation.as_bool()
}
/// Get the action to whether calculate external tax or not as a boolean value
fn get_external_tax_action_as_bool(&self) -> bool {
- match self.skip_external_tax_calculation {
- TaxCalculationOverride::Skip => false,
- TaxCalculationOverride::Calculate => true,
- }
+ self.skip_external_tax_calculation.as_bool()
}
/// Calculate the net amount for the order
@@ -250,20 +208,22 @@ impl AmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
- SurchargeCalculationOverride::Skip => self.surcharge_amount,
- SurchargeCalculationOverride::Calculate => None,
+ common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
+ common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
- SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
- SurchargeCalculationOverride::Calculate => None,
+ common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
+ common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
- TaxCalculationOverride::Skip => self.tax_details.as_ref().and_then(|tax_details| {
- tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype)
- }),
- TaxCalculationOverride::Calculate => None,
+ common_enums::TaxCalculationOverride::Skip => {
+ self.tax_details.as_ref().and_then(|tax_details| {
+ tax_details.get_tax_amount(confirm_intent_request.payment_method_subtype)
+ })
+ }
+ common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails {
@@ -277,6 +237,33 @@ impl AmountDetails {
order_tax_amount,
}
}
+
+ pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self {
+ Self {
+ order_amount: req
+ .order_amount()
+ .unwrap_or(self.order_amount.into())
+ .into(),
+ currency: req.currency().unwrap_or(self.currency),
+ shipping_cost: req.shipping_cost().or(self.shipping_cost),
+ tax_details: req
+ .order_tax_amount()
+ .map(|order_tax_amount| TaxDetails {
+ default: Some(diesel_models::DefaultTax { order_tax_amount }),
+ payment_method_type: None,
+ })
+ .or(self.tax_details),
+ skip_external_tax_calculation: req
+ .skip_external_tax_calculation()
+ .unwrap_or(self.skip_external_tax_calculation),
+ skip_surcharge_calculation: req
+ .skip_surcharge_calculation()
+ .unwrap_or(self.skip_surcharge_calculation),
+ surcharge_amount: req.surcharge_amount().or(self.surcharge_amount),
+ tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge),
+ amount_captured: self.amount_captured,
+ }
+ }
}
#[cfg(feature = "v2")]
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index b0ffe519d63..9b6b6fe5572 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -1,4 +1,3 @@
-use common_enums as storage_enums;
#[cfg(feature = "v2")]
use common_utils::ext_traits::{Encode, ValueExt};
use common_utils::{
@@ -14,8 +13,6 @@ use common_utils::{
MinorUnit,
},
};
-#[cfg(feature = "v2")]
-use diesel_models::types::OrderDetailsWithAmount;
use diesel_models::{
PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew,
};
@@ -29,6 +26,8 @@ use time::PrimitiveDateTime;
#[cfg(all(feature = "v1", feature = "olap"))]
use super::payment_attempt::PaymentAttempt;
use super::PaymentIntent;
+#[cfg(feature = "v2")]
+use crate::address::Address;
use crate::{
behaviour, errors,
merchant_key_store::MerchantKeyStore,
@@ -44,7 +43,7 @@ pub trait PaymentIntentInterface {
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
async fn insert_payment_intent(
@@ -52,7 +51,7 @@ pub trait PaymentIntentInterface {
state: &KeyManagerState,
new: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
#[cfg(feature = "v1")]
@@ -62,7 +61,7 @@ pub trait PaymentIntentInterface {
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
#[cfg(feature = "v2")]
@@ -71,7 +70,7 @@ pub trait PaymentIntentInterface {
state: &KeyManagerState,
id: &id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -81,7 +80,7 @@ pub trait PaymentIntentInterface {
merchant_id: &id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -91,7 +90,7 @@ pub trait PaymentIntentInterface {
merchant_id: &id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -109,7 +108,7 @@ pub trait PaymentIntentInterface {
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -117,7 +116,7 @@ pub trait PaymentIntentInterface {
&self,
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
- storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, errors::StorageError>;
}
@@ -133,39 +132,52 @@ pub struct CustomerData {
#[derive(Debug, Clone, Serialize)]
pub struct PaymentIntentUpdateFields {
pub amount: Option<MinorUnit>,
- pub currency: Option<storage_enums::Currency>,
- pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub status: storage_enums::IntentStatus,
- pub customer_id: Option<id_type::CustomerId>,
- pub shipping_address: Option<Encryptable<Secret<serde_json::Value>>>,
- pub billing_address: Option<Encryptable<Secret<serde_json::Value>>>,
- pub return_url: Option<String>,
- pub description: Option<String>,
- pub statement_descriptor: Option<String>,
- pub order_details: Option<Vec<pii::SecretSerdeValue>>,
+ pub currency: Option<common_enums::Currency>,
+ pub shipping_cost: Option<MinorUnit>,
+ pub tax_details: Option<diesel_models::TaxDetails>,
+ pub skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>,
+ pub skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>,
+ pub surcharge_amount: Option<MinorUnit>,
+ pub tax_on_surcharge: Option<MinorUnit>,
+ pub routing_algorithm_id: Option<id_type::RoutingId>,
+ pub capture_method: Option<common_enums::CaptureMethod>,
+ pub authentication_type: Option<common_enums::AuthenticationType>,
+ pub billing_address: Option<Encryptable<Address>>,
+ pub shipping_address: Option<Encryptable<Address>>,
+ pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
+ pub description: Option<common_utils::types::Description>,
+ pub return_url: Option<common_utils::types::Url>,
+ pub setup_future_usage: Option<common_enums::FutureUsage>,
+ pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>,
+ pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
+ pub order_details: Option<Vec<Secret<diesel_models::types::OrderDetailsWithAmount>>>,
+ pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
pub metadata: Option<pii::SecretSerdeValue>,
- pub payment_confirm_source: Option<storage_enums::PaymentSource>,
- pub updated_by: String,
+ pub connector_metadata: Option<pii::SecretSerdeValue>,
+ pub feature_metadata: Option<diesel_models::types::FeatureMetadata>,
+ pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>,
+ pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>,
pub session_expiry: Option<PrimitiveDateTime>,
- pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
- pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
- pub merchant_order_reference_id: Option<String>,
- pub is_payment_processor_token_flow: Option<bool>,
+ pub request_external_three_ds_authentication:
+ Option<common_enums::External3dsAuthenticationRequest>,
+
+ // updated_by is set internally, field not present in request
+ pub updated_by: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize)]
pub struct PaymentIntentUpdateFields {
pub amount: MinorUnit,
- pub currency: storage_enums::Currency,
- pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub status: storage_enums::IntentStatus,
+ pub currency: common_enums::Currency,
+ pub setup_future_usage: Option<common_enums::FutureUsage>,
+ pub status: common_enums::IntentStatus,
pub customer_id: Option<id_type::CustomerId>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub return_url: Option<String>,
- pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_country: Option<common_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub description: Option<String>,
pub statement_descriptor_name: Option<String>,
@@ -173,7 +185,7 @@ pub struct PaymentIntentUpdateFields {
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<serde_json::Value>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
- pub payment_confirm_source: Option<storage_enums::PaymentSource>,
+ pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub updated_by: String,
pub fingerprint_id: Option<String>,
pub session_expiry: Option<PrimitiveDateTime>,
@@ -190,7 +202,7 @@ pub struct PaymentIntentUpdateFields {
#[derive(Debug, Clone, Serialize)]
pub enum PaymentIntentUpdate {
ResponseUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
return_url: Option<String>,
updated_by: String,
@@ -204,7 +216,7 @@ pub enum PaymentIntentUpdate {
Update(Box<PaymentIntentUpdateFields>),
PaymentCreateUpdate {
return_url: Option<String>,
- status: Option<storage_enums::IntentStatus>,
+ status: Option<common_enums::IntentStatus>,
customer_id: Option<id_type::CustomerId>,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
@@ -212,13 +224,13 @@ pub enum PaymentIntentUpdate {
updated_by: String,
},
MerchantStatusUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
updated_by: String,
},
PGStatusUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
incremental_authorization_allowed: Option<bool>,
updated_by: String,
},
@@ -228,18 +240,18 @@ pub enum PaymentIntentUpdate {
updated_by: String,
},
StatusAndAttemptUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
active_attempt_id: String,
attempt_count: i16,
updated_by: String,
},
ApproveUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
RejectUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
@@ -257,7 +269,7 @@ pub enum PaymentIntentUpdate {
shipping_address_id: Option<String>,
},
ManualUpdate {
- status: Option<storage_enums::IntentStatus>,
+ status: Option<common_enums::IntentStatus>,
updated_by: String,
},
SessionResponseUpdate {
@@ -273,72 +285,41 @@ pub enum PaymentIntentUpdate {
pub enum PaymentIntentUpdate {
/// PreUpdate tracker of ConfirmIntent
ConfirmIntent {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
active_attempt_id: id_type::GlobalAttemptId,
updated_by: String,
},
/// PostUpdate tracker of ConfirmIntent
ConfirmIntentPostUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
updated_by: String,
},
/// SyncUpdate of ConfirmIntent in PostUpdateTrackers
SyncUpdate {
- status: storage_enums::IntentStatus,
+ status: common_enums::IntentStatus,
updated_by: String,
},
-}
-
-#[cfg(feature = "v2")]
-#[derive(Clone, Debug, Default)]
-pub struct PaymentIntentUpdateInternal {
- pub amount: Option<MinorUnit>,
- pub currency: Option<storage_enums::Currency>,
- pub status: Option<storage_enums::IntentStatus>,
- pub amount_captured: Option<MinorUnit>,
- pub customer_id: Option<id_type::CustomerId>,
- pub return_url: Option<String>,
- pub setup_future_usage: Option<storage_enums::FutureUsage>,
- pub off_session: Option<bool>,
- pub metadata: Option<pii::SecretSerdeValue>,
- pub modified_at: Option<PrimitiveDateTime>,
- pub active_attempt_id: Option<id_type::GlobalAttemptId>,
- pub description: Option<String>,
- pub statement_descriptor: Option<String>,
- pub order_details: Option<Vec<pii::SecretSerdeValue>>,
- pub attempt_count: Option<i16>,
- pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
- pub payment_confirm_source: Option<storage_enums::PaymentSource>,
- pub updated_by: String,
- pub surcharge_applicable: Option<bool>,
- pub authorization_count: Option<i32>,
- pub session_expiry: Option<PrimitiveDateTime>,
- pub request_external_three_ds_authentication: Option<bool>,
- pub frm_metadata: Option<pii::SecretSerdeValue>,
- pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
- pub billing_address: Option<Encryptable<Secret<serde_json::Value>>>,
- pub shipping_address: Option<Encryptable<Secret<serde_json::Value>>>,
- pub merchant_order_reference_id: Option<String>,
- pub is_payment_processor_token_flow: Option<bool>,
+ /// UpdateIntent
+ UpdateIntent(Box<PaymentIntentUpdateFields>),
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Default)]
pub struct PaymentIntentUpdateInternal {
pub amount: Option<MinorUnit>,
- pub currency: Option<storage_enums::Currency>,
- pub status: Option<storage_enums::IntentStatus>,
+ pub currency: Option<common_enums::Currency>,
+ pub status: Option<common_enums::IntentStatus>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<id_type::CustomerId>,
pub return_url: Option<String>,
- pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub setup_future_usage: Option<common_enums::FutureUsage>,
pub off_session: Option<bool>,
pub metadata: Option<serde_json::Value>,
pub billing_address_id: Option<String>,
pub shipping_address_id: Option<String>,
pub modified_at: Option<PrimitiveDateTime>,
pub active_attempt_id: Option<String>,
- pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_country: Option<common_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub description: Option<String>,
pub statement_descriptor_name: Option<String>,
@@ -348,7 +329,7 @@ pub struct PaymentIntentUpdateInternal {
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
- pub payment_confirm_source: Option<storage_enums::PaymentSource>,
+ pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
@@ -379,49 +360,185 @@ impl From<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal {
status: Some(status),
active_attempt_id: Some(active_attempt_id),
modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
updated_by,
},
+
PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {
status: Some(status),
active_attempt_id: None,
modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
updated_by,
},
PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self {
status: Some(status),
active_attempt_id: None,
modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: None,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
updated_by,
},
- }
- }
-}
+ PaymentIntentUpdate::UpdateIntent(boxed_intent) => {
+ let PaymentIntentUpdateFields {
+ amount,
+ currency,
+ shipping_cost,
+ tax_details,
+ skip_external_tax_calculation,
+ skip_surcharge_calculation,
+ surcharge_amount,
+ tax_on_surcharge,
+ routing_algorithm_id,
+ capture_method,
+ authentication_type,
+ billing_address,
+ shipping_address,
+ customer_present,
+ description,
+ return_url,
+ setup_future_usage,
+ apply_mit_exemption,
+ statement_descriptor,
+ order_details,
+ allowed_payment_method_types,
+ metadata,
+ connector_metadata,
+ feature_metadata,
+ payment_link_config,
+ request_incremental_authorization,
+ session_expiry,
+ frm_metadata,
+ request_external_three_ds_authentication,
+ updated_by,
+ } = *boxed_intent;
+ Self {
+ status: None,
+ active_attempt_id: None,
+ modified_at: common_utils::date_time::now(),
-// This conversion is required for the `apply_changeset` function used for mockdb
-#[cfg(feature = "v2")]
-impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
- fn from(payment_intent_update: PaymentIntentUpdate) -> Self {
- match payment_intent_update {
- PaymentIntentUpdate::ConfirmIntent {
- status,
- active_attempt_id,
- updated_by,
- } => Self {
- status: Some(status),
- active_attempt_id: Some(active_attempt_id),
- updated_by,
- ..Default::default()
- },
- PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => Self {
- status: Some(status),
- updated_by,
- ..Default::default()
- },
- PaymentIntentUpdate::SyncUpdate { status, updated_by } => Self {
- status: Some(status),
- updated_by,
- ..Default::default()
- },
+ amount,
+ currency,
+ shipping_cost,
+ tax_details,
+ skip_external_tax_calculation: skip_external_tax_calculation
+ .map(|val| val.as_bool()),
+ surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()),
+ surcharge_amount,
+ tax_on_surcharge,
+ routing_algorithm_id,
+ capture_method,
+ authentication_type,
+ billing_address: billing_address.map(Encryption::from),
+ shipping_address: shipping_address.map(Encryption::from),
+ customer_present: customer_present.map(|val| val.as_bool()),
+ description,
+ return_url,
+ setup_future_usage,
+ apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()),
+ statement_descriptor,
+ order_details,
+ allowed_payment_method_types: allowed_payment_method_types
+ .map(|allowed_payment_method_types| {
+ allowed_payment_method_types.encode_to_value()
+ })
+ .and_then(|r| r.ok().map(Secret::new)),
+ metadata,
+ connector_metadata,
+ feature_metadata,
+ payment_link_config,
+ request_incremental_authorization,
+ session_expiry,
+ frm_metadata,
+ request_external_three_ds_authentication:
+ request_external_three_ds_authentication.map(|val| val.as_bool()),
+
+ updated_by,
+ }
+ }
}
}
}
@@ -623,6 +740,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
}
}
+#[cfg(feature = "v1")]
use diesel_models::{
PaymentIntentUpdate as DieselPaymentIntentUpdate,
PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields,
@@ -814,75 +932,6 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {
}
}
-// TODO: evaluate if we will be using the same update struct for v2 as well, uncomment this and make necessary changes if necessary
-#[cfg(feature = "v2")]
-impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal {
- fn from(value: PaymentIntentUpdateInternal) -> Self {
- todo!()
- // let modified_at = common_utils::date_time::now();
- // let PaymentIntentUpdateInternal {
- // amount,
- // currency,
- // status,
- // amount_captured,
- // customer_id,
- // return_url,
- // setup_future_usage,
- // off_session,
- // metadata,
- // modified_at: _,
- // active_attempt_id,
- // description,
- // statement_descriptor,
- // order_details,
- // attempt_count,
- // frm_merchant_decision,
- // payment_confirm_source,
- // updated_by,
- // surcharge_applicable,
- // authorization_count,
- // session_expiry,
- // request_external_three_ds_authentication,
- // frm_metadata,
- // customer_details,
- // billing_address,
- // merchant_order_reference_id,
- // shipping_address,
- // is_payment_processor_token_flow,
- // } = value;
- // Self {
- // amount,
- // currency,
- // status,
- // amount_captured,
- // customer_id,
- // return_url,
- // setup_future_usage,
- // off_session,
- // metadata,
- // modified_at,
- // active_attempt_id,
- // description,
- // statement_descriptor,
- // order_details,
- // attempt_count,
- // frm_merchant_decision,
- // payment_confirm_source,
- // updated_by,
- // surcharge_applicable,
- // authorization_count,
- // session_expiry,
- // request_external_three_ds_authentication,
- // frm_metadata,
- // customer_details: customer_details.map(Encryption::from),
- // billing_address: billing_address.map(Encryption::from),
- // merchant_order_reference_id,
- // shipping_address: shipping_address.map(Encryption::from),
- // is_payment_processor_token_flow,
- // }
- }
-}
-
#[cfg(feature = "v1")]
impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal {
fn from(value: PaymentIntentUpdateInternal) -> Self {
@@ -989,11 +1038,11 @@ pub struct PaymentIntentListParams {
pub ending_at: Option<PrimitiveDateTime>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<api_models::enums::Connector>>,
- pub currency: Option<Vec<storage_enums::Currency>>,
- pub status: Option<Vec<storage_enums::IntentStatus>>,
- pub payment_method: Option<Vec<storage_enums::PaymentMethod>>,
- pub payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
- pub authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
+ pub currency: Option<Vec<common_enums::Currency>>,
+ pub status: Option<Vec<common_enums::IntentStatus>>,
+ pub payment_method: Option<Vec<common_enums::PaymentMethod>>,
+ pub payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
+ pub authentication_type: Option<Vec<common_enums::AuthenticationType>>,
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
pub profile_id: Option<Vec<id_type::ProfileId>>,
pub customer_id: Option<id_type::CustomerId>,
@@ -1001,7 +1050,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>>,
+ pub card_network: Option<Vec<common_enums::CardNetwork>>,
pub merchant_order_reference_id: Option<String>,
}
@@ -1328,10 +1377,10 @@ impl behaviour::Conversion for PaymentIntent {
tax_on_surcharge: storage_model.tax_on_surcharge,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
- skip_external_tax_calculation: super::TaxCalculationOverride::from(
+ skip_external_tax_calculation: common_enums::TaxCalculationOverride::from(
storage_model.skip_external_tax_calculation,
),
- skip_surcharge_calculation: super::SurchargeCalculationOverride::from(
+ skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::from(
storage_model.surcharge_applicable,
),
amount_captured: storage_model.amount_captured,
@@ -1396,10 +1445,9 @@ impl behaviour::Conversion for PaymentIntent {
.unwrap_or_default(),
authorization_count: storage_model.authorization_count,
session_expiry: storage_model.session_expiry,
- request_external_three_ds_authentication:
- common_enums::External3dsAuthenticationRequest::from(
- storage_model.request_external_three_ds_authentication,
- ),
+ request_external_three_ds_authentication: storage_model
+ .request_external_three_ds_authentication
+ .into(),
frm_metadata: storage_model.frm_metadata,
customer_details: data.customer_details,
billing_address,
@@ -1410,15 +1458,9 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: storage_model.organization_id,
authentication_type: storage_model.authentication_type.unwrap_or_default(),
prerouting_algorithm: storage_model.prerouting_algorithm,
- enable_payment_link: common_enums::EnablePaymentLinkRequest::from(
- storage_model.enable_payment_link,
- ),
- apply_mit_exemption: common_enums::MitExemptionRequest::from(
- storage_model.apply_mit_exemption,
- ),
- customer_present: common_enums::PresenceOfCustomerDuringPayment::from(
- storage_model.customer_present,
- ),
+ enable_payment_link: storage_model.enable_payment_link.into(),
+ apply_mit_exemption: storage_model.apply_mit_exemption.into(),
+ customer_present: storage_model.customer_present.into(),
payment_link_config: storage_model.payment_link_config,
routing_algorithm_id: storage_model.routing_algorithm_id,
})
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
index c43d72ce8de..bbe1a65de86 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
@@ -62,5 +62,8 @@ pub struct PaymentCreateIntent;
#[derive(Debug, Clone)]
pub struct PaymentGetIntent;
+#[derive(Debug, Clone)]
+pub struct PaymentUpdateIntent;
+
#[derive(Debug, Clone)]
pub struct PostSessionTokens;
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 2221055be5a..ba2975349c0 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -124,6 +124,7 @@ Never share your secret api keys. Keep them guarded and secure.
//Routes for payments
routes::payments::payments_create_intent,
routes::payments::payments_get_intent,
+ routes::payments::payments_update_intent,
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
@@ -353,9 +354,11 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
+ api_models::payments::PaymentsUpdateIntentRequest,
api_models::payments::PaymentsIntentResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
+ api_models::payments::AmountDetailsUpdate,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index 4c9d069a458..927f4e69e3a 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -646,6 +646,43 @@ pub fn payments_create_intent() {}
)]
#[cfg(feature = "v2")]
pub fn payments_get_intent() {}
+
+/// Payments - Update Intent
+///
+/// **Update a payment intent object**
+///
+/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
+#[utoipa::path(
+ put,
+ path = "/v2/payments/{id}/update-intent",
+ params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
+ (
+ "X-Profile-Id" = String, Header,
+ description = "Profile ID associated to the payment intent",
+ example = json!({"X-Profile-Id": "pro_abcdefghijklmnop"})
+ ),
+ ),
+ request_body(
+ content = PaymentsUpdateIntentRequest,
+ examples(
+ (
+ "Update a payment intent with minimal fields" = (
+ value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
+ )
+ ),
+ ),
+ ),
+ responses(
+ (status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse),
+ (status = 404, description = "Payment Intent Not Found")
+ ),
+ tag = "Payments",
+ operation_id = "Update a Payment Intent",
+ security(("api_key" = [])),
+)]
+#[cfg(feature = "v2")]
+pub fn payments_update_intent() {}
+
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 99b0a635400..dea0ca35123 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1001,12 +1001,13 @@ where
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_intent_operation_core<F, Req, Op, D>(
state: &SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
key_store: domain::MerchantKeyStore,
operation: Op,
req: Req,
+ payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>)>
where
@@ -1023,8 +1024,6 @@ where
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
- let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id.clone());
-
tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
let operations::GetTrackerResponse { mut payment_data } = operation
@@ -1051,6 +1050,22 @@ where
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
+
+ let (_operation, payment_data) = operation
+ .to_update_tracker()?
+ .update_trackers(
+ state,
+ req_state,
+ payment_data,
+ customer.clone(),
+ merchant_account.storage_scheme,
+ None,
+ &key_store,
+ None,
+ header_payload,
+ )
+ .await?;
+
Ok((payment_data, req, customer))
}
@@ -1436,6 +1451,7 @@ pub async fn payments_intent_core<F, Res, Req, Op, D>(
key_store: domain::MerchantKeyStore,
operation: Op,
req: Req,
+ payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
@@ -1453,6 +1469,7 @@ where
key_store,
operation.clone(),
req,
+ payment_id,
header_payload.clone(),
)
.await?;
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 5cdfff60b45..f957b939acf 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -36,6 +36,8 @@ pub mod payment_confirm_intent;
pub mod payment_create_intent;
#[cfg(feature = "v2")]
pub mod payment_get_intent;
+#[cfg(feature = "v2")]
+pub mod payment_update_intent;
#[cfg(feature = "v2")]
pub mod payment_get;
@@ -52,6 +54,8 @@ pub use self::payment_get::PaymentGet;
#[cfg(feature = "v2")]
pub use self::payment_get_intent::PaymentGetIntent;
pub use self::payment_response::PaymentResponse;
+#[cfg(feature = "v2")]
+pub use self::payment_update_intent::PaymentUpdateIntent;
#[cfg(feature = "v1")]
pub use self::{
payment_approve::PaymentApprove, payment_cancel::PaymentCancel,
diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs
new file mode 100644
index 00000000000..f8ce03d558e
--- /dev/null
+++ b/crates/router/src/core/payments/operations/payment_update_intent.rs
@@ -0,0 +1,447 @@
+use std::marker::PhantomData;
+
+use api_models::{enums::FrmSuggestion, payments::PaymentsUpdateIntentRequest};
+use async_trait::async_trait;
+use common_utils::{
+ errors::CustomResult,
+ ext_traits::{Encode, ValueExt},
+ types::keymanager::ToEncryptable,
+};
+use diesel_models::types::FeatureMetadata;
+use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payments::payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields},
+ ApiModelToDieselModelConvertor,
+};
+use masking::PeekInterface;
+use router_env::{instrument, tracing};
+
+use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
+use crate::{
+ core::{
+ errors::{self, RouterResult},
+ payments::{
+ self,
+ operations::{self, ValidateStatusForOperation},
+ },
+ },
+ db::errors::StorageErrorExt,
+ routes::{app::ReqState, SessionState},
+ types::{
+ api,
+ domain::{self, types as domain_types},
+ storage::{self, enums},
+ },
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct PaymentUpdateIntent;
+
+impl ValidateStatusForOperation for PaymentUpdateIntent {
+ /// Validate if the current operation can be performed on the current status of the payment intent
+ fn validate_status_for_operation(
+ &self,
+ intent_status: common_enums::IntentStatus,
+ ) -> Result<(), errors::ApiErrorResponse> {
+ match intent_status {
+ common_enums::IntentStatus::RequiresPaymentMethod => Ok(()),
+ common_enums::IntentStatus::Succeeded
+ | common_enums::IntentStatus::Failed
+ | common_enums::IntentStatus::Cancelled
+ | common_enums::IntentStatus::Processing
+ | common_enums::IntentStatus::RequiresCustomerAction
+ | common_enums::IntentStatus::RequiresMerchantAction
+ | common_enums::IntentStatus::RequiresCapture
+ | common_enums::IntentStatus::PartiallyCaptured
+ | common_enums::IntentStatus::RequiresConfirmation
+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable => {
+ Err(errors::ApiErrorResponse::PaymentUnexpectedState {
+ current_flow: format!("{self:?}"),
+ field_name: "status".to_string(),
+ current_value: intent_status.to_string(),
+ states: ["requires_payment_method".to_string()].join(", "),
+ })
+ }
+ }
+ }
+}
+
+impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for &PaymentUpdateIntent {
+ type Data = payments::PaymentIntentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<
+ &(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
+ > {
+ Ok(*self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+ fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>)> {
+ Ok(*self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+}
+
+impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for PaymentUpdateIntent {
+ type Data = payments::PaymentIntentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<
+ &(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
+ > {
+ Ok(self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
+ {
+ Ok(self)
+ }
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>> {
+ Ok(self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
+ {
+ Ok(self)
+ }
+}
+
+type PaymentsUpdateIntentOperation<'b, F> =
+ BoxedOperation<'b, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>;
+
+#[async_trait]
+impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
+ for PaymentUpdateIntent
+{
+ #[instrument(skip_all)]
+ async fn get_trackers<'a>(
+ &'a self,
+ state: &'a SessionState,
+ payment_id: &common_utils::id_type::GlobalPaymentId,
+ request: &PaymentsUpdateIntentRequest,
+ merchant_account: &domain::MerchantAccount,
+ _profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+ let storage_scheme = merchant_account.storage_scheme;
+ let payment_intent = db
+ .find_payment_intent_by_id(key_manager_state, payment_id, key_store, storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ self.validate_status_for_operation(payment_intent.status)?;
+
+ let PaymentsUpdateIntentRequest {
+ amount_details,
+ routing_algorithm_id,
+ capture_method,
+ authentication_type,
+ billing,
+ shipping,
+ customer_present,
+ description,
+ return_url,
+ setup_future_usage,
+ apply_mit_exemption,
+ statement_descriptor,
+ order_details,
+ allowed_payment_method_types,
+ metadata,
+ connector_metadata,
+ feature_metadata,
+ payment_link_config,
+ request_incremental_authorization,
+ session_expiry,
+ frm_metadata,
+ request_external_three_ds_authentication,
+ } = request.clone();
+
+ let batch_encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent),
+ domain_types::CryptoOperation::BatchEncrypt(
+ hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable(
+ hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent {
+ shipping_address: shipping.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new),
+ billing_address: billing.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new),
+ customer_details: None,
+ },
+ ),
+ ),
+ common_utils::types::keymanager::Identifier::Merchant(merchant_account.get_id().to_owned()),
+ key_store.key.peek(),
+ )
+ .await
+ .and_then(|val| val.try_into_batchoperation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details".to_string())?;
+
+ let decrypted_payment_intent =
+ hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting payment intent details")?;
+
+ let order_details = order_details.clone().map(|order_details| {
+ order_details
+ .into_iter()
+ .map(|order_detail| {
+ masking::Secret::new(
+ diesel_models::types::OrderDetailsWithAmount::convert_from(order_detail),
+ )
+ })
+ .collect()
+ });
+
+ let session_expiry = session_expiry.map(|expiry| {
+ payment_intent
+ .created_at
+ .saturating_add(time::Duration::seconds(i64::from(expiry)))
+ });
+
+ let updated_amount_details = match amount_details {
+ Some(details) => payment_intent.amount_details.update_from_request(&details),
+ None => payment_intent.amount_details,
+ };
+
+ let payment_intent = hyperswitch_domain_models::payments::PaymentIntent {
+ amount_details: updated_amount_details,
+ description: description.or(payment_intent.description),
+ return_url: return_url.or(payment_intent.return_url),
+ metadata: metadata.or(payment_intent.metadata),
+ statement_descriptor: statement_descriptor.or(payment_intent.statement_descriptor),
+ modified_at: common_utils::date_time::now(),
+ order_details,
+ connector_metadata: connector_metadata.or(payment_intent.connector_metadata),
+ feature_metadata: (feature_metadata
+ .map(FeatureMetadata::convert_from)
+ .or(payment_intent.feature_metadata)),
+ updated_by: storage_scheme.to_string(),
+ request_incremental_authorization: request_incremental_authorization
+ .unwrap_or(payment_intent.request_incremental_authorization),
+ session_expiry: session_expiry.unwrap_or(payment_intent.session_expiry),
+ request_external_three_ds_authentication: request_external_three_ds_authentication
+ .unwrap_or(payment_intent.request_external_three_ds_authentication),
+ frm_metadata: frm_metadata.or(payment_intent.frm_metadata),
+ billing_address: decrypted_payment_intent
+ .billing_address
+ .as_ref()
+ .map(|data| {
+ data.clone()
+ .deserialize_inner_value(|value| value.parse_value("Address"))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to decode billing address")?,
+ shipping_address: decrypted_payment_intent
+ .shipping_address
+ .as_ref()
+ .map(|data| {
+ data.clone()
+ .deserialize_inner_value(|value| value.parse_value("Address"))
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to decode shipping address")?,
+ capture_method: capture_method.unwrap_or(payment_intent.capture_method),
+ authentication_type: authentication_type.unwrap_or(payment_intent.authentication_type),
+ payment_link_config: payment_link_config
+ .map(ApiModelToDieselModelConvertor::convert_from)
+ .or(payment_intent.payment_link_config),
+ apply_mit_exemption: apply_mit_exemption.unwrap_or(payment_intent.apply_mit_exemption),
+ customer_present: customer_present.unwrap_or(payment_intent.customer_present),
+ routing_algorithm_id: routing_algorithm_id.or(payment_intent.routing_algorithm_id),
+ allowed_payment_method_types: allowed_payment_method_types
+ .or(payment_intent.allowed_payment_method_types),
+ ..payment_intent
+ };
+
+ let payment_data = payments::PaymentIntentData {
+ flow: PhantomData,
+ payment_intent,
+ sessions_token: vec![],
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse { payment_data };
+
+ Ok(get_trackers_response)
+ }
+}
+
+#[async_trait]
+impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
+ for PaymentUpdateIntent
+{
+ #[instrument(skip_all)]
+ async fn update_trackers<'b>(
+ &'b self,
+ state: &'b SessionState,
+ _req_state: ReqState,
+ mut payment_data: payments::PaymentIntentData<F>,
+ _customer: Option<domain::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
+ _updated_customer: Option<storage::CustomerUpdate>,
+ key_store: &domain::MerchantKeyStore,
+ _frm_suggestion: Option<FrmSuggestion>,
+ _header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<(
+ PaymentsUpdateIntentOperation<'b, F>,
+ payments::PaymentIntentData<F>,
+ )>
+ where
+ F: 'b + Send,
+ {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+
+ let intent = payment_data.payment_intent.clone();
+
+ let payment_intent_update =
+ PaymentIntentUpdate::UpdateIntent(Box::new(PaymentIntentUpdateFields {
+ amount: Some(intent.amount_details.order_amount),
+ currency: Some(intent.amount_details.currency),
+ shipping_cost: intent.amount_details.shipping_cost,
+ skip_external_tax_calculation: Some(
+ intent.amount_details.skip_external_tax_calculation,
+ ),
+ skip_surcharge_calculation: Some(intent.amount_details.skip_surcharge_calculation),
+ surcharge_amount: intent.amount_details.surcharge_amount,
+ tax_on_surcharge: intent.amount_details.tax_on_surcharge,
+ routing_algorithm_id: intent.routing_algorithm_id,
+ capture_method: Some(intent.capture_method),
+ authentication_type: Some(intent.authentication_type),
+ billing_address: intent.billing_address,
+ shipping_address: intent.shipping_address,
+ customer_present: Some(intent.customer_present),
+ description: intent.description,
+ return_url: intent.return_url,
+ setup_future_usage: Some(intent.setup_future_usage),
+ apply_mit_exemption: Some(intent.apply_mit_exemption),
+ statement_descriptor: intent.statement_descriptor,
+ order_details: intent.order_details,
+ allowed_payment_method_types: intent.allowed_payment_method_types,
+ metadata: intent.metadata,
+ connector_metadata: intent.connector_metadata,
+ feature_metadata: intent.feature_metadata,
+ payment_link_config: intent.payment_link_config,
+ request_incremental_authorization: Some(intent.request_incremental_authorization),
+ session_expiry: Some(intent.session_expiry),
+ frm_metadata: intent.frm_metadata,
+ request_external_three_ds_authentication: Some(
+ intent.request_external_three_ds_authentication,
+ ),
+ updated_by: intent.updated_by,
+ tax_details: intent.amount_details.tax_details,
+ }));
+
+ let new_payment_intent = db
+ .update_payment_intent(
+ key_manager_state,
+ payment_data.payment_intent,
+ payment_intent_update,
+ key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not update Intent")?;
+
+ payment_data.payment_intent = new_payment_intent;
+
+ Ok((Box::new(self), payment_data))
+ }
+}
+
+impl<F: Send + Clone>
+ ValidateRequest<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
+ for PaymentUpdateIntent
+{
+ #[instrument(skip_all)]
+ fn validate_request<'a, 'b>(
+ &'b self,
+ _request: &PaymentsUpdateIntentRequest,
+ merchant_account: &'a domain::MerchantAccount,
+ ) -> RouterResult<operations::ValidateResult> {
+ Ok(operations::ValidateResult {
+ merchant_id: merchant_account.get_id().to_owned(),
+ storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
+ })
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Send> Domain<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
+ for PaymentUpdateIntent
+{
+ #[instrument(skip_all)]
+ async fn get_customer_details<'a>(
+ &'a self,
+ _state: &SessionState,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<
+ (
+ BoxedOperation<'a, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>,
+ Option<domain::Customer>,
+ ),
+ errors::StorageError,
+ > {
+ Ok((Box::new(self), None))
+ }
+
+ #[instrument(skip_all)]
+ async fn make_pm_data<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ _storage_scheme: enums::MerchantStorageScheme,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _customer: &Option<domain::Customer>,
+ _business_profile: &domain::Profile,
+ ) -> RouterResult<(
+ PaymentsUpdateIntentOperation<'a, F>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+ )> {
+ Ok((Box::new(self), None, None))
+ }
+
+ #[instrument(skip_all)]
+ async fn perform_routing<'a>(
+ &'a self,
+ _merchant_account: &domain::MerchantAccount,
+ _business_profile: &domain::Profile,
+ _state: &SessionState,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ _mechant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
+ Ok(api::ConnectorCallType::Skip)
+ }
+
+ #[instrument(skip_all)]
+ async fn guard_payment_against_blocklist<'a>(
+ &'a self,
+ _state: &SessionState,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ ) -> CustomResult<bool, errors::ApiErrorResponse> {
+ Ok(false)
+ }
+}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index fb8962117c1..6e277ed460f 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -3526,12 +3526,8 @@ impl
currency: intent_amount_details.currency,
shipping_cost: attempt_amount_details.shipping_cost,
order_tax_amount: attempt_amount_details.order_tax_amount,
- external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from(
- intent_amount_details.skip_external_tax_calculation,
- ),
- surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from(
- intent_amount_details.skip_surcharge_calculation,
- ),
+ external_tax_calculation: intent_amount_details.skip_external_tax_calculation,
+ surcharge_calculation: intent_amount_details.skip_surcharge_calculation,
surcharge_amount: attempt_amount_details.surcharge_amount,
tax_on_surcharge: attempt_amount_details.tax_on_surcharge,
net_amount: attempt_amount_details.net_amount,
@@ -3569,12 +3565,8 @@ impl
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.get_default_tax_amount())),
- external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from(
- intent_amount_details.skip_external_tax_calculation,
- ),
- surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from(
- intent_amount_details.skip_surcharge_calculation,
- ),
+ external_tax_calculation: intent_amount_details.skip_external_tax_calculation,
+ surcharge_calculation: intent_amount_details.skip_surcharge_calculation,
surcharge_amount: attempt_amount_details
.and_then(|attempt| attempt.surcharge_amount)
.or(intent_amount_details.surcharge_amount),
@@ -3629,76 +3621,14 @@ impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails>
order_tax_amount: amount_details.tax_details.and_then(|tax_details| {
tax_details.default.map(|default| default.order_tax_amount)
}),
- external_tax_calculation: common_enums::TaxCalculationOverride::foreign_from(
- amount_details.skip_external_tax_calculation,
- ),
- surcharge_calculation: common_enums::SurchargeCalculationOverride::foreign_from(
- amount_details.skip_surcharge_calculation,
- ),
+ external_tax_calculation: amount_details.skip_external_tax_calculation,
+ surcharge_calculation: amount_details.skip_surcharge_calculation,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
}
}
}
-#[cfg(feature = "v2")]
-impl ForeignFrom<common_enums::TaxCalculationOverride>
- for hyperswitch_domain_models::payments::TaxCalculationOverride
-{
- fn foreign_from(tax_calculation_override: common_enums::TaxCalculationOverride) -> Self {
- match tax_calculation_override {
- common_enums::TaxCalculationOverride::Calculate => Self::Calculate,
- common_enums::TaxCalculationOverride::Skip => Self::Skip,
- }
- }
-}
-
-#[cfg(feature = "v2")]
-impl ForeignFrom<hyperswitch_domain_models::payments::TaxCalculationOverride>
- for common_enums::TaxCalculationOverride
-{
- fn foreign_from(
- tax_calculation_override: hyperswitch_domain_models::payments::TaxCalculationOverride,
- ) -> Self {
- match tax_calculation_override {
- hyperswitch_domain_models::payments::TaxCalculationOverride::Calculate => {
- Self::Calculate
- }
- hyperswitch_domain_models::payments::TaxCalculationOverride::Skip => Self::Skip,
- }
- }
-}
-
-#[cfg(feature = "v2")]
-impl ForeignFrom<common_enums::SurchargeCalculationOverride>
- for hyperswitch_domain_models::payments::SurchargeCalculationOverride
-{
- fn foreign_from(
- surcharge_calculation_override: common_enums::SurchargeCalculationOverride,
- ) -> Self {
- match surcharge_calculation_override {
- common_enums::SurchargeCalculationOverride::Calculate => Self::Calculate,
- common_enums::SurchargeCalculationOverride::Skip => Self::Skip,
- }
- }
-}
-
-#[cfg(feature = "v2")]
-impl ForeignFrom<hyperswitch_domain_models::payments::SurchargeCalculationOverride>
- for common_enums::SurchargeCalculationOverride
-{
- fn foreign_from(
- surcharge_calculation_override: hyperswitch_domain_models::payments::SurchargeCalculationOverride,
- ) -> Self {
- match surcharge_calculation_override {
- hyperswitch_domain_models::payments::SurchargeCalculationOverride::Calculate => {
- Self::Calculate
- }
- hyperswitch_domain_models::payments::SurchargeCalculationOverride::Skip => Self::Skip,
- }
- }
-}
-
#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::PaymentLinkConfigRequestForPayments
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index be24084bcc0..75b06e7f813 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -555,6 +555,10 @@ impl Payments {
web::resource("/get-intent")
.route(web::get().to(payments::payments_get_intent)),
)
+ .service(
+ web::resource("/update-intent")
+ .route(web::put().to(payments::payments_update_intent)),
+ )
.service(
web::resource("/create-external-sdk-tokens")
.route(web::post().to(payments::payments_connector_session)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 762a5227207..614676e203f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -142,6 +142,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsCreateIntent
| Flow::PaymentsGetIntent
| Flow::PaymentsPostSessionTokens
+ | Flow::PaymentsUpdateIntent
| Flow::PaymentStartRedirection => Self::Payments,
Flow::PayoutsCreate
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 27a5462c05e..7a8e65e0604 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -118,6 +118,9 @@ pub async fn payments_create_intent(
return api::log_and_return_error_response(err);
}
};
+ let global_payment_id =
+ common_utils::id_type::GlobalPaymentId::generate(&state.conf.cell_information.id.clone());
+
Box::pin(api::server_wrap(
flow,
state,
@@ -138,6 +141,7 @@ pub async fn payments_create_intent(
auth.key_store,
payments::operations::PaymentIntentCreate,
req,
+ global_payment_id.clone(),
header_payload.clone(),
)
},
@@ -178,6 +182,8 @@ pub async fn payments_get_intent(
id: path.into_inner(),
};
+ let global_payment_id = payload.id.clone();
+
Box::pin(api::server_wrap(
flow,
state,
@@ -198,6 +204,62 @@ pub async fn payments_get_intent(
auth.key_store,
payments::operations::PaymentGetIntent,
req,
+ global_payment_id.clone(),
+ header_payload.clone(),
+ )
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdateIntent, payment_id))]
+pub async fn payments_update_intent(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<payment_types::PaymentsUpdateIntentRequest>,
+ path: web::Path<common_utils::id_type::GlobalPaymentId>,
+) -> impl Responder {
+ use hyperswitch_domain_models::payments::PaymentIntentData;
+
+ let flow = Flow::PaymentsUpdateIntent;
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => {
+ return api::log_and_return_error_response(err);
+ }
+ };
+
+ let internal_payload = internal_payload_types::PaymentsGenericRequestWithResourceId {
+ global_payment_id: path.into_inner(),
+ payload: json_payload.into_inner(),
+ };
+
+ let global_payment_id = internal_payload.global_payment_id.clone();
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ internal_payload,
+ |state, auth: auth::AuthenticationData, req, req_state| {
+ payments::payments_intent_core::<
+ api_types::PaymentUpdateIntent,
+ payment_types::PaymentsIntentResponse,
+ _,
+ _,
+ PaymentIntentData<api_types::PaymentUpdateIntent>,
+ >(
+ state,
+ req_state,
+ auth.merchant_account,
+ auth.profile,
+ auth.key_store,
+ payments::operations::PaymentUpdateIntent,
+ req.payload,
+ global_payment_id.clone(),
header_payload.clone(),
)
},
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 524712f1ca0..8be423c037b 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -19,13 +19,15 @@ pub use api_models::payments::{
VerifyResponse, WalletData,
};
#[cfg(feature = "v2")]
-pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsIntentResponse};
+pub use api_models::payments::{
+ PaymentsCreateIntentRequest, PaymentsIntentResponse, PaymentsUpdateIntentRequest,
+};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent,
- PaymentGetIntent, PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject,
- SdkSessionUpdate, Session, SetupMandate, Void,
+ PaymentGetIntent, PaymentMethodToken, PaymentUpdateIntent, PostProcessing, PostSessionTokens,
+ PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 27ddc10766d..3ae2de9ffdf 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -168,6 +168,8 @@ pub enum Flow {
PaymentsCreateIntent,
/// Payments Get Intent flow
PaymentsGetIntent,
+ /// Payments Update Intent flow
+ PaymentsUpdateIntent,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index ebf75a58b2c..fe64136b743 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -10,6 +10,8 @@ use common_utils::{
};
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
+#[cfg(feature = "v1")]
+use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate;
#[cfg(feature = "olap")]
use diesel_models::query::generics::db_metrics;
#[cfg(all(feature = "v1", feature = "olap"))]
@@ -23,11 +25,7 @@ use diesel_models::schema_v2::{
payment_intent::dsl as pi_dsl,
};
use diesel_models::{
- enums::MerchantStorageScheme,
- kv,
- payment_intent::{
- PaymentIntent as DieselPaymentIntent, PaymentIntentUpdate as DieselPaymentIntentUpdate,
- },
+ enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent,
};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
|
2024-11-06T09:26:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added `update-intent` API for payments
### 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)?
-->
1. Intent Create Response:
```json
{
"id": "12345_pay_01930aca908b76b086927c61ad1fb724",
"status": "requires_payment_method",
"amount_details": {
"order_amount": 100,
"currency": "USD",
"shipping_cost": null,
"order_tax_amount": null,
"skip_external_tax_calculation": "Skip",
"skip_surcharge_calculation": "Skip",
"surcharge_amount": null,
"tax_on_surcharge": null
},
"client_secret": "12345_pay_01930aca908b76b086927c61ad1fb724_secret_01930aca908c71c3b6233716f1caede1",
"merchant_reference_id": null,
"routing_algorithm_id": null,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"billing": null,
"shipping": null,
"customer_id": null,
"customer_present": "Present",
"description": null,
"return_url": null,
"setup_future_usage": "on_session",
"apply_mit_exemption": "Skip",
"statement_descriptor": null,
"order_details": null,
"allowed_payment_method_types": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"payment_link_enabled": "Skip",
"payment_link_config": null,
"request_incremental_authorization": "default",
"expires_on": "2024-11-08T08:16:07.724Z",
"frm_metadata": null,
"request_external_three_ds_authentication": "Skip"
}
```
2a. Update Intent Request
```
curl --location --request PUT 'http://localhost:8080/v2/payments/12345_pay_0193921b3f687473ae7aa7e2b2cabc83/update-intent' \
--header 'Content-Type: application/json' \
--header 'x-profile-id: pro_tUJFXjqpFC8MaEF5t8zE' \
--header 'api-key: dev_FW2koArhbGpoUIZNrRPHNIbdgi7TZuCq5V3OHNlQYZOMuy8gU4hu5mrR5IivoOwh' \
--data-raw '{
"amount_details": {
"order_amount": 6590,
"currency": "AED",
"shipping_cost": 123,
"order_tax_amount": 123,
"skip_external_tax_calculation": "skip",
"skip_surcharge_calculation": "skip",
"surcharge_amount": 123,
"tax_on_surcharge": 123
},
"capture_method": "automatic",
"authentication_type": "three_ds",
"billing": {
"address": {
"city": "New York",
"country": "AF",
"line1": "123, King Street",
"line2": "Powelson Avenue",
"line3": "Bridgewater",
"zip": "08807",
"state": "New York",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+1"
},
"email": "blue@blue.com"
},
"shipping": {
"address": {
"city": "New York",
"country": "AF",
"line1": "123, King Street",
"line2": "Powelson Avenue",
"line3": "Bridgewater",
"zip": "08807",
"state": "New York",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+1"
},
"email": "blue@blue.com"
},
"customer_present": "present",
"description": "It'\''s my first payment request",
"return_url": "https://hyperswitch.io",
"setup_future_usage": "off_session",
"apply_mit_exemption": "Apply",
"statement_descriptor": "Hyperswitch Router",
"order_details": [{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000,
"product_img_link": "https://dummy-img-link.com"
}],
"allowed_payment_method_types": [
"ach"
],
"metadata": {},
"connector_metadata": {
"apple_pay": {
"session_token_data": {
"payment_processing_certificate": "<string>",
"payment_processing_certificate_key": "<string>",
"payment_processing_details_at": "Hyperswitch",
"certificate": "<string>",
"certificate_keys": "<string>",
"merchant_identifier": "<string>",
"display_name": "<string>",
"initiative": "web",
"initiative_context": "<string>",
"merchant_business_country": "AF"
}
},
"airwallex": {
"payload": "<string>"
},
"noon": {
"order_category": "<string>"
}
},
"feature_metadata": {
"redirect_response": {
"param": "<string>",
"json_payload": {}
},
"search_tags": [
"<string>"
]
},
"payment_link_config": {
"theme": "#4E6ADD",
"logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg",
"seller_name": "hyperswitch",
"sdk_layout": "accordion",
"display_sdk_only": true,
"enabled_saved_payment_method": true,
"transaction_details": [
{
"key": "Policy-Number",
"value": "297472368473924",
"ui_configuration": {
"position": 5,
"is_key_bold": true,
"is_value_bold": true
}
}
]
},
"request_incremental_authorization": "true",
"session_expiry": 1000,
"frm_metadata": {},
"request_external_three_ds_authentication": "Enable"
}'
```
2b. Update Intent Response
```json
{
"id": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83",
"status": "requires_payment_method",
"amount_details": {
"order_amount": 6590,
"currency": "AED",
"shipping_cost": 123,
"order_tax_amount": 123,
"external_tax_calculation": "skip",
"surcharge_calculation": "skip",
"surcharge_amount": 123,
"tax_on_surcharge": 123
},
"client_secret": "12345_pay_0193921b3f687473ae7aa7e2b2cabc83_secret_0193921b3f727390b03af88afb886f68",
"profile_id": "pro_tUJFXjqpFC8MaEF5t8zE",
"merchant_reference_id": null,
"routing_algorithm_id": null,
"capture_method": "automatic",
"authentication_type": "three_ds",
"billing": {
"address": {
"city": "New York",
"country": "AF",
"line1": "123, King Street",
"line2": "Powelson Avenue",
"line3": "Bridgewater",
"zip": "08807",
"state": "New York",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+1"
},
"email": "blue@blue.com"
},
"shipping": {
"address": {
"city": "New York",
"country": "AF",
"line1": "123, King Street",
"line2": "Powelson Avenue",
"line3": "Bridgewater",
"zip": "08807",
"state": "New York",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+1"
},
"email": "blue@blue.com"
},
"customer_id": null,
"customer_present": "present",
"description": "It's my first payment request",
"return_url": "https://hyperswitch.io/",
"setup_future_usage": "on_session",
"apply_mit_exemption": "Apply",
"statement_descriptor": "Hyperswitch Router",
"order_details": [
{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount": 69000,
"requires_shipping": null,
"product_img_link": "https://dummy-img-link.com",
"product_id": null,
"category": null,
"sub_category": null,
"brand": null,
"product_type": null,
"product_tax_code": null
}
],
"allowed_payment_method_types": [
"ach"
],
"metadata": {},
"connector_metadata": {
"apple_pay": {
"session_token_data": {
"payment_processing_certificate": "<string>",
"payment_processing_certificate_key": "<string>",
"payment_processing_details_at": "Hyperswitch",
"certificate": "<string>",
"certificate_keys": "<string>",
"merchant_identifier": "<string>",
"display_name": "<string>",
"initiative": "web",
"initiative_context": "<string>",
"merchant_business_country": "AF"
}
},
"airwallex": {
"payload": "<string>"
},
"noon": {
"order_category": "<string>"
}
},
"feature_metadata": {
"redirect_response": {
"param": "<string>",
"json_payload": {}
},
"search_tags": [
"e3846ee6d6368937023c2bbd84565e5fee999118fb8f5e16a31d1129471d130a"
]
},
"payment_link_enabled": "Enable",
"payment_link_config": {
"theme": "#4E6ADD",
"logo": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg",
"seller_name": "hyperswitch",
"sdk_layout": "accordion",
"display_sdk_only": true,
"enabled_saved_payment_method": true,
"hide_card_nickname_field": null,
"show_card_form_by_default": null,
"transaction_details": [
{
"key": "Policy-Number",
"value": "297472368473924",
"ui_configuration": {
"position": 5,
"is_key_bold": true,
"is_value_bold": true
}
}
]
},
"request_incremental_authorization": "true",
"expires_on": "2024-12-04T14:54:39.539Z",
"frm_metadata": {},
"request_external_three_ds_authentication": "Enable"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
15f873bd1296169149987041f4008b0afe2ac2aa
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6456
|
Bug: reduce cargo build jobs to 3 from 4
try reducing cargo build jobs to 3
|
2024-10-28T12:41:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR reduces build jobs to 3 to see if it helps pass Cypress CI checks
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
NA
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
CI should work
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cd6265887adf7c17136e9fb608e97e6dd535e360
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6449
|
Bug: Update broken readme icon
Updating broken readme icon along with reposition of the hero image
|
diff --git a/README.md b/README.md
index ccdd6e19b6d..10fdb6afc76 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@ The single API to access payment ecosystems across 130+ countries</div>
<p align="center">
<a href="https://github.com/juspay/hyperswitch/actions?query=workflow%3ACI+branch%3Amain">
- <img src="https://github.com/juspay/hyperswitch/workflows/CI/badge.svg" />
+ <img src="https://github.com/juspay/hyperswitch/workflows/CI-push/badge.svg" />
</a>
<a href="https://github.com/juspay/hyperswitch/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/juspay/hyperswitch" />
@@ -44,7 +44,6 @@ The single API to access payment ecosystems across 130+ countries</div>
</p>
<hr>
-<img src="./docs/imgs/switch.png" />
Hyperswitch is a community-led, open payments switch designed to empower digital businesses by providing fast, reliable, and affordable access to the best payments infrastructure.
@@ -58,7 +57,8 @@ Here are the components of Hyperswitch that deliver the whole solution:
Jump in and contribute to these repositories to help improve and expand Hyperswitch!
-<br>
+<img src="./docs/imgs/switch.png" />
+
<a href="#Quick Setup">
<h2 id="quick-setup">⚡️ Quick Setup</h2>
|
2024-10-28T05:20:16Z
|
TOC icon and reposition of the hero image in readme
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Updated the icon of CI Push and repositioned the hero image
closes #6449
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cd6265887adf7c17136e9fb608e97e6dd535e360
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6438
|
Bug: fix: lazy connection pools for dynamic routing service
|
diff --git a/Cargo.lock b/Cargo.lock
index 9ccedba3c39..78ae2d63adb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3126,8 +3126,10 @@ dependencies = [
"dyn-clone",
"error-stack",
"hex",
+ "http-body-util",
"hyper 0.14.30",
"hyper-proxy",
+ "hyper-util",
"hyperswitch_interfaces",
"masking",
"once_cell",
@@ -3959,9 +3961,9 @@ dependencies = [
[[package]]
name = "hyper-util"
-version = "0.1.7"
+version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9"
+checksum = "41296eb09f183ac68eec06e03cdbea2e759633d4067b2f6552fc2e009bcad08b"
dependencies = [
"bytes 1.7.1",
"futures-channel",
@@ -3972,7 +3974,6 @@ dependencies = [
"pin-project-lite",
"socket2",
"tokio 1.40.0",
- "tower",
"tower-service",
"tracing",
]
diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml
index 735ccc5ebfa..12b9dd3b0f3 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", "common_utils/v1"]
-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"]
+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", "dep:hyper-util", "dep:http-body-util"]
[dependencies]
async-trait = "0.1.79"
@@ -38,6 +38,8 @@ 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 }
+hyper-util = { version = "0.1.9", optional = true }
+http-body-util = { version = "0.1.2", optional = true }
# First party crates
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index 2681bffb0ce..343dd80e951 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -6,6 +6,9 @@ use api_models::routing::{
};
use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
+use http_body_util::combinators::UnsyncBoxBody;
+use hyper::body::Bytes;
+use hyper_util::client::legacy::connect::HttpConnector;
use serde;
use success_rate::{
success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig,
@@ -13,7 +16,7 @@ use success_rate::{
CurrentBlockThreshold as DynamicCurrentThreshold, LabelWithStatus,
UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
-use tonic::transport::Channel;
+use tonic::Status;
#[allow(
missing_docs,
unused_qualifications,
@@ -40,11 +43,13 @@ pub enum DynamicRoutingError {
SuccessRateBasedRoutingFailure(String),
}
+type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>;
+
/// 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>>,
+ pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>,
}
/// Contains the Dynamic Routing Client Config
@@ -68,11 +73,14 @@ impl DynamicRoutingClientConfig {
pub async fn get_dynamic_routing_connection(
self,
) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
+ let client =
+ hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
+ .http2_only(true)
+ .build_http();
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))
+ let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?;
+ Some(SuccessRateCalculatorClient::with_origin(client, uri))
}
Self::Disabled => None,
};
@@ -102,7 +110,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {
}
#[async_trait::async_trait]
-impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> {
+impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> {
async fn calculate_success_rate(
&self,
id: String,
|
2024-10-25T10:47:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Previously hyperswitch server was panicking, if it wasn't able to establish a connection with dynamic_routing service. We have fixed this by establishing lazy connection pools and not established channel(which was previously). Which will insure hyperswitch server to run even when the connection isn't established.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 on my local.
<img width="1728" alt="Screenshot 2024-10-25 at 4 15 03 PM" src="https://github.com/user-attachments/assets/a7a1d6c8-8c6c-4b35-ae3a-b05b6af9f9bc">
This can't be tested on Integ as we don't have this service on integ.
Can't be tested on sbx as well, as it will require the pods to be killed. and a re-establishment of connection.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
aaac9aa97d1b00d50bec4e02efb0658956463398
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6439
|
Bug: fix(authz): Proper descriptions for parents
Currently descriptions for parent groups in invite page of control center are not entity specific. That means, customers in description will be visible for profile level users when it shouldn't.
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index a2c76ecc394..e0df36a3349 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,8 +2,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest,
- RoleInfoResponseNew, RoleInfoWithGroupsResponse, UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, GroupsAndResources, ListRolesAtEntityLevelRequest,
+ ListRolesRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithParents,
+ UpdateRoleRequest,
},
AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest,
UpdateUserRoleRequest,
@@ -22,6 +23,8 @@ common_utils::impl_api_event_type!(
RoleInfoResponseNew,
RoleInfoWithGroupsResponse,
ListUsersInEntityRequest,
- ListRolesRequest
+ ListRolesRequest,
+ GroupsAndResources,
+ RoleInfoWithParents
)
);
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 885ec455e4c..7c877cd7477 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,5 +1,6 @@
-pub use common_enums::PermissionGroup;
-use common_enums::{EntityType, RoleScope};
+use common_enums::{
+ EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope,
+};
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
@@ -22,6 +23,21 @@ pub struct RoleInfoWithGroupsResponse {
pub role_scope: RoleScope,
}
+#[derive(Debug, serde::Serialize)]
+pub struct RoleInfoWithParents {
+ pub role_id: String,
+ pub parent_groups: Vec<ParentGroupInfo>,
+ pub role_name: String,
+ pub role_scope: RoleScope,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct ParentGroupInfo {
+ pub name: ParentGroup,
+ pub description: String,
+ pub scopes: Vec<PermissionScope>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ListRolesRequest {
pub entity_type: Option<EntityType>,
@@ -57,3 +73,9 @@ pub struct MinimalRoleInfo {
pub role_id: String,
pub role_name: String,
}
+
+#[derive(Debug, serde::Serialize)]
+pub struct GroupsAndResources {
+ pub groups: Vec<PermissionGroup>,
+ pub resources: Vec<Resource>,
+}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index c103153eec8..faae71eda22 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2884,10 +2884,15 @@ pub enum PermissionGroup {
AnalyticsView,
UsersView,
UsersManage,
+ // TODO: To be deprecated, make sure DB is migrated before removing
MerchantDetailsView,
+ // TODO: To be deprecated, make sure DB is migrated before removing
MerchantDetailsManage,
+ // TODO: To be deprecated, make sure DB is migrated before removing
OrganizationManage,
ReconOps,
+ AccountView,
+ AccountManage,
}
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)]
@@ -2897,14 +2902,12 @@ pub enum ParentGroup {
Workflows,
Analytics,
Users,
- #[serde(rename = "MerchantAccess")]
- Merchant,
- #[serde(rename = "OrganizationAccess")]
- Organization,
Recon,
+ Account,
}
-#[derive(Clone, Copy, Eq, PartialEq, Hash)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
pub enum Resource {
Payment,
Refund,
@@ -2925,10 +2928,11 @@ pub enum Resource {
Recon,
}
-#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)]
+#[serde(rename_all = "snake_case")]
pub enum PermissionScope {
- Read,
- Write,
+ Read = 0,
+ Write = 1,
}
/// Name of banks supported by Hyperswitch
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 284be4ab4ba..27c1e2ae494 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -1,6 +1,9 @@
use std::collections::{HashMap, HashSet};
-use api_models::{user as user_api, user_role as user_role_api};
+use api_models::{
+ user as user_api,
+ user_role::{self as user_role_api, role as role_api},
+};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
organization::OrganizationBridge,
@@ -16,7 +19,11 @@ use crate::{
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
- authorization::{info, permission_groups::PermissionGroupExt, roles},
+ authorization::{
+ info,
+ permission_groups::{ParentGroupExt, PermissionGroupExt},
+ roles,
+ },
ApplicationResponse,
},
types::domain,
@@ -72,6 +79,40 @@ pub async fn get_authorization_info_with_group_tag(
))
}
+pub async fn get_parent_group_info(
+ state: SessionState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<Vec<role_api::ParentGroupInfo>> {
+ 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::InvalidRoleId)?;
+
+ let parent_groups = ParentGroup::get_descriptions_for_groups(
+ role_info.get_entity_type(),
+ PermissionGroup::iter().collect(),
+ )
+ .into_iter()
+ .map(|(parent_group, description)| role_api::ParentGroupInfo {
+ name: parent_group.clone(),
+ description,
+ scopes: PermissionGroup::iter()
+ .filter_map(|group| (group.parent() == parent_group).then_some(group.scope()))
+ // TODO: Remove this hashset conversion when merhant access
+ // and organization access groups are removed
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect(),
+ })
+ .collect::<Vec<_>>();
+
+ Ok(ApplicationResponse::Json(parent_groups))
+}
+
pub async fn update_user_role(
state: SessionState,
user_from_token: auth::UserFromToken,
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index b5b5cab421f..1d37f7ac8d1 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -1,5 +1,7 @@
+use std::collections::HashSet;
+
use api_models::user_role::role::{self as role_api};
-use common_enums::{EntityType, RoleScope};
+use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope};
use common_utils::generate_id_with_default_len;
use diesel_models::role::{RoleNew, RoleUpdate};
use error_stack::{report, ResultExt};
@@ -9,7 +11,10 @@ use crate::{
routes::{app::ReqState, SessionState},
services::{
authentication::{blacklist, UserFromToken},
- authorization::roles::{self, predefined_roles::PREDEFINED_ROLES},
+ authorization::{
+ permission_groups::{ParentGroupExt, PermissionGroupExt},
+ roles::{self, predefined_roles::PREDEFINED_ROLES},
+ },
ApplicationResponse,
},
types::domain::user::RoleName,
@@ -19,7 +24,7 @@ use crate::{
pub async fn get_role_from_token_with_groups(
state: SessionState,
user_from_token: UserFromToken,
-) -> UserResponse<Vec<role_api::PermissionGroup>> {
+) -> UserResponse<Vec<PermissionGroup>> {
let role_info = user_from_token
.get_role_info_from_db(&state)
.await
@@ -30,6 +35,29 @@ pub async fn get_role_from_token_with_groups(
Ok(ApplicationResponse::Json(permissions))
}
+pub async fn get_groups_and_resources_for_role_from_token(
+ state: SessionState,
+ user_from_token: UserFromToken,
+) -> UserResponse<role_api::GroupsAndResources> {
+ let role_info = user_from_token.get_role_info_from_db(&state).await?;
+
+ let groups = role_info
+ .get_permission_groups()
+ .into_iter()
+ .collect::<Vec<_>>();
+ let resources = groups
+ .iter()
+ .flat_map(|group| group.resources())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+
+ Ok(ApplicationResponse::Json(role_api::GroupsAndResources {
+ groups,
+ resources,
+ }))
+}
+
pub async fn create_role(
state: SessionState,
user_from_token: UserFromToken,
@@ -111,6 +139,52 @@ pub async fn get_role_with_groups(
))
}
+pub async fn get_parent_info_for_role(
+ state: SessionState,
+ user_from_token: UserFromToken,
+ role: role_api::GetRoleRequest,
+) -> UserResponse<role_api::RoleInfoWithParents> {
+ let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
+ &state,
+ &role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleId.into());
+ }
+
+ let parent_groups = ParentGroup::get_descriptions_for_groups(
+ role_info.get_entity_type(),
+ role_info.get_permission_groups().to_vec(),
+ )
+ .into_iter()
+ .map(|(parent_group, description)| role_api::ParentGroupInfo {
+ name: parent_group.clone(),
+ description,
+ scopes: role_info
+ .get_permission_groups()
+ .iter()
+ .filter_map(|group| (group.parent() == parent_group).then_some(group.scope()))
+ // TODO: Remove this hashset conversion when merhant access
+ // and organization access groups are removed
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect(),
+ })
+ .collect();
+
+ Ok(ApplicationResponse::Json(role_api::RoleInfoWithParents {
+ role_id: role.role_id,
+ parent_groups,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }))
+}
+
pub async fn update_role(
state: SessionState,
user_from_token: UserFromToken,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index f11840edf63..f54895ce7da 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1819,9 +1819,14 @@ impl User {
web::resource("/permission_info")
.route(web::get().to(user_role::get_authorization_info)),
)
+ // TODO: To be deprecated
.service(
web::resource("/module/list").route(web::get().to(user_role::get_role_information)),
)
+ .service(
+ web::resource("/parent/list")
+ .route(web::get().to(user_role::get_parent_group_info)),
+ )
.service(
web::resource("/update").route(web::post().to(user::update_user_account_details)),
)
@@ -2017,6 +2022,9 @@ impl User {
.route(web::get().to(user_role::get_role_from_token))
.route(web::post().to(user_role::create_role)),
)
+ .service(web::resource("/v2").route(
+ web::get().to(user_role::get_groups_and_resources_for_role_from_token),
+ ))
// TODO: To be deprecated
.service(
web::resource("/v2/list")
@@ -2039,6 +2047,10 @@ impl User {
web::resource("/{role_id}")
.route(web::get().to(user_role::get_role))
.route(web::put().to(user_role::update_role)),
+ )
+ .service(
+ web::resource("/{role_id}/v2")
+ .route(web::get().to(user_role::get_parent_info_for_role)),
),
);
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index a0c5c0f9902..ac17cf80210 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -263,10 +263,13 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
+ | Flow::GetRoleV2
| Flow::GetRoleFromToken
+ | Flow::GetRoleFromTokenV2
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
+ | Flow::GetParentGroupInfo
| Flow::AcceptInvitationsV2
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 74847f06474..9910cef3950 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -55,6 +55,26 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -
.await
}
+pub async fn get_groups_and_resources_for_role_from_token(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::GetRoleFromTokenV2;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| async move {
+ role_core::get_groups_and_resources_for_role_from_token(state, user).await
+ },
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn create_role(
state: web::Data<AppState>,
req: HttpRequest,
@@ -100,6 +120,31 @@ pub async fn get_role(
.await
}
+pub async fn get_parent_info_for_role(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::GetRoleV2;
+ let request_payload = user_role_api::role::GetRoleRequest {
+ role_id: path.into_inner(),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ request_payload,
+ |state, user, payload, _| async move {
+ role_core::get_parent_info_for_role(state, user, payload).await
+ },
+ &auth::JWTAuth {
+ permission: Permission::ProfileUserRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn update_role(
state: web::Data<AppState>,
req: HttpRequest,
@@ -226,6 +271,28 @@ pub async fn get_role_information(
.await
}
+pub async fn get_parent_group_info(
+ state: web::Data<AppState>,
+ http_req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::GetParentGroupInfo;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &http_req,
+ (),
+ |state, user_from_token, _, _| async move {
+ user_role_core::get_parent_group_info(state, user_from_token).await
+ },
+ &auth::JWTAuth {
+ permission: Permission::ProfileUserRead,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn list_users_in_lineage(
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 dba96dac188..bd987e2fe9a 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -37,32 +37,13 @@ fn get_group_description(group: PermissionGroup) -> &'static str {
PermissionGroup::AnalyticsView => "View Analytics",
PermissionGroup::UsersView => "View Users",
PermissionGroup::UsersManage => "Manage and invite Users to the Team",
- PermissionGroup::MerchantDetailsView => "View Merchant Details",
- PermissionGroup::MerchantDetailsManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
+ PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details",
+ PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
PermissionGroup::ReconOps => "View and manage reconciliation reports",
}
}
-pub fn get_parent_name(group: PermissionGroup) -> ParentGroup {
- match group {
- PermissionGroup::OperationsView | PermissionGroup::OperationsManage => {
- ParentGroup::Operations
- }
- PermissionGroup::ConnectorsView | PermissionGroup::ConnectorsManage => {
- ParentGroup::Connectors
- }
- PermissionGroup::WorkflowsView | PermissionGroup::WorkflowsManage => ParentGroup::Workflows,
- PermissionGroup::AnalyticsView => ParentGroup::Analytics,
- PermissionGroup::UsersView | PermissionGroup::UsersManage => ParentGroup::Users,
- PermissionGroup::MerchantDetailsView | PermissionGroup::MerchantDetailsManage => {
- ParentGroup::Merchant
- }
- PermissionGroup::OrganizationManage => ParentGroup::Organization,
- PermissionGroup::ReconOps => ParentGroup::Recon,
- }
-}
-
pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
match group {
ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
@@ -70,8 +51,7 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
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::Account => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
ParentGroup::Recon => "View and manage reconciliation reports",
}
}
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index 3d1a0c8ea5b..57c385565a8 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -1,4 +1,9 @@
-use common_enums::{ParentGroup, PermissionGroup, PermissionScope, Resource};
+use std::collections::HashMap;
+
+use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource};
+use strum::IntoEnumIterator;
+
+use super::permissions::{self, ResourceExt};
pub trait PermissionGroupExt {
fn scope(&self) -> PermissionScope;
@@ -15,7 +20,8 @@ impl PermissionGroupExt for PermissionGroup {
| Self::WorkflowsView
| Self::AnalyticsView
| Self::UsersView
- | Self::MerchantDetailsView => PermissionScope::Read,
+ | Self::MerchantDetailsView
+ | Self::AccountView => PermissionScope::Read,
Self::OperationsManage
| Self::ConnectorsManage
@@ -23,7 +29,8 @@ impl PermissionGroupExt for PermissionGroup {
| Self::UsersManage
| Self::MerchantDetailsManage
| Self::OrganizationManage
- | Self::ReconOps => PermissionScope::Write,
+ | Self::ReconOps
+ | Self::AccountManage => PermissionScope::Write,
}
}
@@ -34,9 +41,12 @@ impl PermissionGroupExt for PermissionGroup {
Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
Self::AnalyticsView => ParentGroup::Analytics,
Self::UsersView | Self::UsersManage => ParentGroup::Users,
- Self::MerchantDetailsView | Self::MerchantDetailsManage => ParentGroup::Merchant,
- Self::OrganizationManage => ParentGroup::Organization,
Self::ReconOps => ParentGroup::Recon,
+ Self::MerchantDetailsView
+ | Self::OrganizationManage
+ | Self::MerchantDetailsManage
+ | Self::AccountView
+ | Self::AccountManage => ParentGroup::Account,
}
}
@@ -52,10 +62,14 @@ impl PermissionGroupExt for PermissionGroup {
Self::ConnectorsView => vec![Self::ConnectorsView],
Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
- Self::WorkflowsView => vec![Self::WorkflowsView],
- Self::WorkflowsManage => vec![Self::WorkflowsView, Self::WorkflowsManage],
+ Self::WorkflowsView => vec![Self::WorkflowsView, Self::ConnectorsView],
+ Self::WorkflowsManage => vec![
+ Self::WorkflowsView,
+ Self::WorkflowsManage,
+ Self::ConnectorsView,
+ ],
- Self::AnalyticsView => vec![Self::AnalyticsView],
+ Self::AnalyticsView => vec![Self::AnalyticsView, Self::OperationsView],
Self::UsersView => vec![Self::UsersView],
Self::UsersManage => {
@@ -70,12 +84,19 @@ impl PermissionGroupExt for PermissionGroup {
}
Self::OrganizationManage => vec![Self::OrganizationManage],
+
+ Self::AccountView => vec![Self::AccountView],
+ Self::AccountManage => vec![Self::AccountView, Self::AccountManage],
}
}
}
pub trait ParentGroupExt {
fn resources(&self) -> Vec<Resource>;
+ fn get_descriptions_for_groups(
+ entity_type: EntityType,
+ groups: Vec<PermissionGroup>,
+ ) -> HashMap<ParentGroup, String>;
}
impl ParentGroupExt for ParentGroup {
@@ -86,10 +107,38 @@ impl ParentGroupExt for ParentGroup {
Self::Workflows => WORKFLOWS.to_vec(),
Self::Analytics => ANALYTICS.to_vec(),
Self::Users => USERS.to_vec(),
- Self::Merchant | Self::Organization => ACCOUNT.to_vec(),
+ Self::Account => ACCOUNT.to_vec(),
Self::Recon => RECON.to_vec(),
}
}
+
+ fn get_descriptions_for_groups(
+ entity_type: EntityType,
+ groups: Vec<PermissionGroup>,
+ ) -> HashMap<Self, String> {
+ Self::iter()
+ .filter_map(|parent| {
+ let scopes = groups
+ .iter()
+ .filter(|group| group.parent() == parent)
+ .map(|group| group.scope())
+ .max()?;
+
+ let resources = parent
+ .resources()
+ .iter()
+ .filter(|res| res.entities().iter().any(|entity| entity <= &entity_type))
+ .map(|res| permissions::get_resource_name(res, &entity_type))
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ Some((
+ parent,
+ format!("{} {}", permissions::get_scope_name(&scopes), resources),
+ ))
+ })
+ .collect()
+ }
}
pub static OPERATIONS: [Resource; 8] = [
@@ -105,11 +154,10 @@ pub static OPERATIONS: [Resource; 8] = [
pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account];
-pub static WORKFLOWS: [Resource; 5] = [
+pub static WORKFLOWS: [Resource; 4] = [
Resource::Routing,
Resource::ThreeDsDecisionManager,
Resource::SurchargeDecisionManager,
- Resource::Connector,
Resource::Account,
];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 0521db7acc1..6e472d55623 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -73,3 +73,34 @@ generate_permissions! {
},
]
}
+
+pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'static str {
+ match (resource, entity_type) {
+ (Resource::Payment, _) => "Payments",
+ (Resource::Refund, _) => "Refunds",
+ (Resource::Dispute, _) => "Disputes",
+ (Resource::Mandate, _) => "Mandates",
+ (Resource::Customer, _) => "Customers",
+ (Resource::Payout, _) => "Payouts",
+ (Resource::ApiKey, _) => "Api Keys",
+ (Resource::Connector, _) => "Payment Processors, Payout Processors, Fraud & Risk Managers",
+ (Resource::Routing, _) => "Routing",
+ (Resource::ThreeDsDecisionManager, _) => "3DS Decision Manager",
+ (Resource::SurchargeDecisionManager, _) => "Surcharge Decision Manager",
+ (Resource::Analytics, _) => "Analytics",
+ (Resource::Report, _) => "Operation Reports",
+ (Resource::User, _) => "Users",
+ (Resource::WebhookEvent, _) => "Webhook Events",
+ (Resource::Recon, _) => "Reconciliation Reports",
+ (Resource::Account, EntityType::Profile) => "Business Profile Account",
+ (Resource::Account, EntityType::Merchant) => "Merchant Account",
+ (Resource::Account, EntityType::Organization) => "Organization Account",
+ }
+}
+
+pub fn get_scope_name(scope: &PermissionScope) -> &'static str {
+ match scope {
+ PermissionScope::Read => "View",
+ PermissionScope::Write => "View and Manage",
+ }
+}
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 33a1d5f53ca..39f6d47f824 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -24,7 +24,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOps,
],
@@ -48,6 +50,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
@@ -75,7 +78,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOps,
],
@@ -105,7 +110,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
PermissionGroup::ReconOps,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
@@ -128,6 +135,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
role_name: "merchant_view_only".to_string(),
@@ -148,6 +156,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
role_name: "merchant_iam".to_string(),
@@ -168,7 +177,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
role_name: "merchant_developer".to_string(),
@@ -191,6 +202,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
role_name: "merchant_operator".to_string(),
@@ -210,6 +222,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
role_name: "customer_support".to_string(),
@@ -237,7 +250,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(),
role_name: "profile_admin".to_string(),
@@ -259,6 +274,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(),
role_name: "profile_view_only".to_string(),
@@ -279,6 +295,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(),
role_name: "profile_iam".to_string(),
@@ -299,7 +316,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
+ PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(),
role_name: "profile_developer".to_string(),
@@ -322,6 +341,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(),
role_name: "profile_operator".to_string(),
@@ -341,6 +361,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
+ PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(),
role_name: "profile_customer_support".to_string(),
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 8d853ded338..652ce2b81db 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -374,6 +374,8 @@ pub enum Flow {
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
+ /// Get Parent Group Info
+ GetParentGroupInfo,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
@@ -382,8 +384,12 @@ pub enum Flow {
ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
+ /// Get parent info for role
+ GetRoleV2,
/// Get role from token
GetRoleFromToken,
+ /// Get resources and groups for role from token
+ GetRoleFromTokenV2,
/// Update user role
UpdateUserRole,
/// Create merchant account for user in a org
|
2024-10-25T12:17:59Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Make new APIs to replace
- `/user/role/{{role_id}}` -> `/user/role/{{role_id}}/v2`
- `/user/role` -> `/user/role/v2`
- `/user/module/list` -> `/user/parent/list`
The new APIs will have proper description and parent info which has entity level context unlike the previous APIs.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #6439.
## How did you test 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. Parent List
```
curl --location 'http://localhost:8080/user/parent/list' \
--header 'Authorization: JWT' \
```
```json
[
{
"name": "Operations",
"description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Organization Account",
"scopes": [
"write",
"read"
]
},
{
"name": "Recon",
"description": "View and Manage Reconciliation Reports",
"scopes": [
"write"
]
},
{
"name": "Analytics",
"description": "View Analytics, Operation Reports, Organization Account",
"scopes": [
"read"
]
},
{
"name": "Workflows",
"description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Organization Account",
"scopes": [
"write",
"read"
]
},
{
"name": "Users",
"description": "View and Manage Users, Organization Account",
"scopes": [
"read",
"write"
]
},
{
"name": "Account",
"description": "View and Manage Organization Account, Api Keys, Webhook Events",
"scopes": [
"read",
"write"
]
},
{
"name": "Connectors",
"description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Organization Account",
"scopes": [
"write",
"read"
]
}
]
```
The descriptions and scopes in the above response will change with respect the role.
2. Get Role V2
```
curl --location 'http://localhost:8080/user/role/merchant_admin/v2' \
--header 'Authorization: JWT' \
```
```json
{
"role_id": "merchant_admin",
"parent_groups": [
{
"name": "Users",
"description": "View and Manage Users, Merchant Account",
"scopes": [
"read",
"write"
]
},
{
"name": "Connectors",
"description": "View and Manage Payment Processors, Payout Processors, Fraud & Risk Managers, Merchant Account",
"scopes": [
"read",
"write"
]
},
{
"name": "Recon",
"description": "View and Manage Reconciliation Reports",
"scopes": [
"write"
]
},
{
"name": "Account",
"description": "View and Manage Merchant Account, Api Keys, Webhook Events",
"scopes": [
"read",
"write"
]
},
{
"name": "Workflows",
"description": "View and Manage Routing, 3DS Decision Manager, Surcharge Decision Manager, Merchant Account",
"scopes": [
"write",
"read"
]
},
{
"name": "Analytics",
"description": "View Analytics, Operation Reports, Merchant Account",
"scopes": [
"read"
]
},
{
"name": "Operations",
"description": "View and Manage Payments, Refunds, Mandates, Disputes, Customers, Payouts, Operation Reports, Merchant Account",
"scopes": [
"read",
"write"
]
}
],
"role_name": "merchant_admin",
"role_scope": "organization"
}
```
3. Get Role from Token V2
```
curl --location 'http://localhost:8080/user/role/v2' \
--header 'Authorization: JWT' \
```
```
{
"groups": [
"connectors_manage",
"account_manage",
"users_manage",
"merchant_details_manage",
"merchant_details_view",
"workflows_manage",
"analytics_view",
"operations_view",
"organization_manage",
"connectors_view",
"recon_ops",
"users_view",
"workflows_view",
"account_view",
"operations_manage"
],
"resources": [
"routing",
"customer",
"payout",
"api_key",
"refund",
"connector",
"user",
"mandate",
"analytics",
"account",
"surcharge_decision_manager",
"payment",
"webhook_event",
"recon",
"three_ds_decision_manager",
"dispute",
"report"
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
98567569c1c61648eebf0ad7a1ab58bba967b427
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6436
|
Bug: chore(users): change entity_type column of roles to non-optional
Make entity-type in roles non-optional
|
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index 3fb64e645d6..8199bd3979c 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -18,7 +18,7 @@ pub struct Role {
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
- pub entity_type: Option<enums::EntityType>,
+ pub entity_type: enums::EntityType,
}
#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -35,7 +35,7 @@ pub struct RoleNew {
pub created_by: String,
pub last_modified_at: PrimitiveDateTime,
pub last_modified_by: String,
- pub entity_type: Option<enums::EntityType>,
+ pub entity_type: enums::EntityType,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8d2dfc47b62..e2ab676b2d3 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1235,7 +1235,7 @@ diesel::table! {
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
- entity_type -> Nullable<Varchar>,
+ entity_type -> Varchar,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index b5e895cde79..5651bf95dd9 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1181,7 +1181,7 @@ diesel::table! {
#[max_length = 64]
last_modified_by -> Varchar,
#[max_length = 64]
- entity_type -> Nullable<Varchar>,
+ entity_type -> Varchar,
}
}
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index b5b5cab421f..e43f23674e9 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -64,7 +64,7 @@ pub async fn create_role(
org_id: user_from_token.org_id,
groups: req.groups,
scope: req.role_scope,
- entity_type: Some(EntityType::Merchant),
+ entity_type: EntityType::Merchant,
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id,
created_at: now,
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index ce009d38a9e..d13508356e5 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -354,7 +354,7 @@ impl RoleInterface for MockDb {
None => true,
};
- matches_merchant && role.org_id == *org_id && role.entity_type == entity_type
+ matches_merchant && role.org_id == *org_id && Some(role.entity_type) == entity_type
})
.take(limit_usize)
.cloned()
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 63d547bfa67..bf66eb92466 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -119,7 +119,7 @@ impl From<diesel_models::role::Role> for RoleInfo {
role_name: role.role_name,
groups: role.groups.into_iter().map(Into::into).collect(),
scope: role.scope,
- entity_type: role.entity_type.unwrap_or(EntityType::Merchant),
+ entity_type: role.entity_type,
is_invitable: true,
is_deletable: true,
is_updatable: true,
diff --git a/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql
new file mode 100644
index 00000000000..60dfa892e60
--- /dev/null
+++ b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/down.sql
@@ -0,0 +1,4 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE roles ALTER COLUMN entity_type DROP DEFAULT;
+
+ALTER TABLE roles ALTER COLUMN entity_type DROP NOT NULL;
\ No newline at end of file
diff --git a/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql
new file mode 100644
index 00000000000..564a026184e
--- /dev/null
+++ b/migrations/2024-10-24-123318_update-entity-type-column-in-roles/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+UPDATE roles SET entity_type = 'merchant' WHERE entity_type IS NULL;
+
+ALTER TABLE roles ALTER COLUMN entity_type SET DEFAULT 'merchant';
+
+ALTER TABLE roles ALTER COLUMN entity_type SET NOT NULL;
\ No newline at end of file
|
2024-10-25T09:20:18Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Earlier entity-type column in roles table was optional , after this change the column will be non-optional with default value as Merchant
### Additional Changes
- [ ] This PR modifies the API contract
- [X] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Request :
```
curl 'http://localhost:8080/user/role' \
-H 'authorization: Bearer JWT \
--data-raw '{"role_scope":"merchant","groups":["operations_manage","connectors_view","connectors_manage"],"role_name":"merch-scope-merch-role"}'
```
Response :
```
{
"role_id": "role_qrQ05Q9pu7czBlDEWnGE",
"groups": [
"operations_manage",
"connectors_view",
"connectors_manage"
],
"role_name": "merch-scope-merch-role",
"role_scope": "merchant"
}
```
Db should have an entry in roles table with role-name as merch-scope-merch-role and entity-type as merchant. All the existing flows should work as before
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8372389671c4aefeb625365d198390df5d8f35a5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6430
|
Bug: fix(analytics): fix refund status filter on dashboard
Whenever Refund Status filter is applied on the analytics section on dashboard, errors are being generated.
The wrong RefundStatus enum has been imported for the RefundStatus filter in RefundFilters struct in this PR: https://github.com/juspay/hyperswitch/pull/2988.
Need to import the correct enum for the same
|
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs
index 8acb51e764c..ef17387d1ea 100644
--- a/crates/api_models/src/analytics/refunds.rs
+++ b/crates/api_models/src/analytics/refunds.rs
@@ -5,7 +5,7 @@ use std::{
use common_utils::id_type;
-use crate::{enums::Currency, refunds::RefundStatus};
+use crate::enums::{Currency, RefundStatus};
#[derive(
Clone,
|
2024-10-24T13:21:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Whenever `Refund Status` filter is applied on the analytics section on dashboard, errors are being generated.
- The wrong `RefundStatus` enum has been imported for the `RefundStatus` filter in `RefundFilters` struct in this PR: [https://github.com/juspay/hyperswitch/pull/2988](https://github.com/juspay/hyperswitch/pull/2988).
- Updated the code to use the correct `RefundStatus` import.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 fix the issue on dashboard whenever refund status filter is applied.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Apply the refund status filter on the dashboard
- Hit the curl:
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--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/129.0.0.0 Safari/537.36' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTkyOTAwOCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.B7sxut7HMs1C7QDRJWqOhQXHbugw4Ev3w8EAzskmzeo' \
--header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-10-16T18:30:00Z",
"endTime": "2024-10-24T13:17:00Z"
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"filters": {
"refund_status": ["success"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"refund_success_rate",
"refund_count",
"refund_success_count",
"refund_processed_amount"
]
}
]'
```
Respoonse:
```bash
{
"queryData": [
{
"refund_success_rate": 100.0,
"refund_count": 1,
"refund_success_count": 1,
"refund_processed_amount": 600,
"currency": null,
"refund_status": null,
"connector": null,
"refund_type": null,
"profile_id": null,
"time_range": {
"start_time": "2024-10-24T00:00:00.000Z",
"end_time": "2024-10-24T23:00:00.000Z"
},
"time_bucket": "2024-10-24 00:00:00"
}
],
"metaData": [
{
"current_time_range": {
"start_time": "2024-10-16T18:30:00.000Z",
"end_time": "2024-10-24T13:17:00.000Z"
}
}
]
}
```
<img width="1332" alt="image" src="https://github.com/user-attachments/assets/bf8d08a6-e2e6-437c-884f-6de6c2bcaae3">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6425
|
Bug: fix(payment_methods): fix merchant payment method list to retain a mca based on connector_name and mca_id
Earlier a connector was occurring twice while doing a session token call for wallets. This PR fixes merchant payment method list to retain a mca based on connector_name and mca_id. So that with every distinct mca_id the connector is listed just once for wallets.
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 84106a87d9b..d5255b5e8c5 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1217,12 +1217,14 @@ pub struct ResponsePaymentMethodIntermediate {
pub card_networks: Option<Vec<api_enums::CardNetwork>>,
pub payment_method: api_enums::PaymentMethod,
pub connector: String,
+ pub merchant_connector_id: String,
}
impl ResponsePaymentMethodIntermediate {
pub fn new(
pm_type: RequestPaymentMethodTypes,
connector: String,
+ merchant_connector_id: String,
pm: api_enums::PaymentMethod,
) -> Self {
Self {
@@ -1231,6 +1233,7 @@ impl ResponsePaymentMethodIntermediate {
card_networks: pm_type.card_networks,
payment_method: pm,
connector,
+ merchant_connector_id,
}
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8419a600f39..b664088a415 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2980,6 +2980,7 @@ pub async fn list_payment_methods(
api_enums::PaymentMethodType::ApplePay,
api_enums::PaymentMethodType::Klarna,
api_enums::PaymentMethodType::Paypal,
+ api_enums::PaymentMethodType::SamsungPay,
]);
let mut chosen = Vec::<api::SessionConnectorData>::new();
@@ -3031,6 +3032,15 @@ pub async fn list_payment_methods(
.connector
.connector_name
.to_string()
+ && first_routable_connector
+ .connector
+ .merchant_connector_id
+ .as_ref()
+ .map(|merchant_connector_id| {
+ *merchant_connector_id.get_string_repr()
+ == intermediate.merchant_connector_id
+ })
+ .unwrap_or_default()
} else {
false
}
@@ -4068,6 +4078,7 @@ pub async fn filter_payment_methods(
let response_pm_type = ResponsePaymentMethodIntermediate::new(
payment_method_object,
connector.clone(),
+ mca_id.get_string_repr().to_string(),
payment_method,
);
resp.push(response_pm_type);
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index fd45c475b6d..749ec52be24 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -5298,7 +5298,10 @@ where
let routing_choice = choice
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
- if connector_data.connector.connector_name == routing_choice.connector.connector_name {
+ if connector_data.connector.connector_name == routing_choice.connector.connector_name
+ && connector_data.connector.merchant_connector_id
+ == routing_choice.connector.merchant_connector_id
+ {
final_list.push(connector_data);
}
}
|
2024-10-23T09:37:30Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Earlier a connector was occurring twice while doing a session token call for wallets. This PR fixes merchant payment method list to retain a mca based on connector_name and mca_id. So that with every distinct mca_id the connector is listed just once for wallets.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and an MCA(with wallets enabled)
- Create an payment_intent
```
Intent Response
{
"payment_id": "pay_NHWegNguTfDH9hxuVj1m",
"merchant_id": "merchant_1729514766",
"status": "requires_payment_method",
"amount": 8500,
"net_amount": 8500,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_NHWegNguTfDH9hxuVj1m_secret_YgCdjC1ZMbdqGBmOOoTP",
"created": "2024-10-21T13:11:49.384Z",
"currency": "USD",
"customer_id": "CustomerX777",
"customer": {
"id": "CustomerX777",
"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": "off_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": "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": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "CustomerX777",
"created_at": 1729516309,
"expires": 1729519909,
"secret": "epk_f7a7e71ac7b246b490d5cc31cb55e5d4"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_M3DqjrGVffJASyys4npr",
"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-21T13:26:49.384Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-21T13:11:49.418Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
- Do a PML call, for the wallets the mca should be listed once for the wallets that support session token flow
```
Merchant PML response
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"stripe"
]
}
],
"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": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "samsung_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"stripe",
"stripe"
]
}
],
"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": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"stripe"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "new_mandate",
"request_external_three_ds_authentication": false,
"collect_shipping_details_from_wallets": false,
"collect_billing_details_from_wallets": false,
"is_tax_calculation_enabled": false
}
```
- Create a MA and 2 same MCA
- Create a payment_intent
- Create a session token, only one google_pay will appear
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-client-platform: ios' \
--header 'api-key: pk_dev_385274838f7c4d66b6571c32756827d6' \
--data '{
"payment_id": "pay_NUmAgcew9X7W8yyBBsIK",
"wallets":[],
"client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99"
}'
```
```
{
"payment_id": "pay_NUmAgcew9X7W8yyBBsIK",
"client_secret": "pay_NUmAgcew9X7W8yyBBsIK_secret_DdDRx8PnhQznkCnVfY99",
"session_token": [
{
"wallet_name": "google_pay",
"merchant_info": {
"merchant_name": "S7"
},
"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": "85.00"
},
"delayed_session_token": false,
"connector": "stripe",
"sdk_next_action": {
"next_action": "confirm"
},
"secrets": null
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4ef48c39b3ed7c1fcda9c850da766a0bdb701335
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## 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">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f56d76ffec7ef6c27417a5df1999af7ccc3f1545
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6416
|
Bug: feat(analytics): implement currency conversion to power multi-currency aggregation
## Current Behaviour
The total amount calculated for all payment analytics buckets related to amounts is incorrect because currency conversion is not being applied before summing the values. As a result, amounts in different currencies are being added together, leading to an inaccurate total.
## Proposed Changes
- introduce `<AMOUNT_RELATED_FIELD>_in_usd` fields to convert and store value in `USD`
- introduce total_in_usd to store the total value in usd
- Generally provide currency_conversion facility to metrics function for other future use cases
|
diff --git a/Cargo.lock b/Cargo.lock
index 26ad619ee0b..8c69154fcea 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -353,6 +353,7 @@ dependencies = [
"bigdecimal",
"common_enums",
"common_utils",
+ "currency_conversion",
"diesel_models",
"error-stack",
"futures 0.3.30",
@@ -363,6 +364,7 @@ dependencies = [
"opensearch",
"reqwest 0.11.27",
"router_env",
+ "rust_decimal",
"serde",
"serde_json",
"sqlx",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index 687d5a2e208..db516c49abd 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -21,6 +21,7 @@ hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces"
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"] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
+currency_conversion = { version = "0.1.0", path = "../currency_conversion" }
#Third Party dependencies
actix-web = "4.5.1"
@@ -34,6 +35,7 @@ futures = "0.3.30"
once_cell = "1.19.0"
opensearch = { version = "2.2.0", features = ["aws-auth"] }
reqwest = { version = "0.11.27", features = ["serde_json"] }
+rust_decimal = "1.35"
serde = { version = "1.0.197", features = ["derive", "rc"] }
serde_json = "1.0.115"
sqlx = { version = "0.8.2", features = ["postgres", "runtime-tokio", "runtime-tokio-native-tls", "time", "bigdecimal"] }
diff --git a/crates/analytics/src/errors.rs b/crates/analytics/src/errors.rs
index 0e39a4ddd92..d7b15a6db11 100644
--- a/crates/analytics/src/errors.rs
+++ b/crates/analytics/src/errors.rs
@@ -12,6 +12,8 @@ pub enum AnalyticsError {
UnknownError,
#[error("Access Forbidden Analytics Error")]
AccessForbiddenError,
+ #[error("Failed to fetch currency exchange rate")]
+ ForexFetchFailed,
}
impl ErrorSwitch<ApiErrorResponse> for AnalyticsError {
@@ -32,6 +34,12 @@ impl ErrorSwitch<ApiErrorResponse> for AnalyticsError {
Self::AccessForbiddenError => {
ApiErrorResponse::Unauthorized(ApiError::new("IR", 0, "Access Forbidden", None))
}
+ Self::ForexFetchFailed => ApiErrorResponse::InternalServerError(ApiError::new(
+ "HE",
+ 0,
+ "Failed to fetch currency exchange rate",
+ None,
+ )),
}
}
}
diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs
index cbb8335cea0..ef3cd3129c4 100644
--- a/crates/analytics/src/payment_intents/accumulator.rs
+++ b/crates/analytics/src/payment_intents/accumulator.rs
@@ -86,7 +86,7 @@ impl PaymentIntentMetricAccumulator for CountAccumulator {
}
impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator {
- type MetricOutput = (Option<u64>, Option<u64>);
+ type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
self.amount = match (
@@ -117,7 +117,7 @@ impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator {
.amount_without_retries
.and_then(|i| u64::try_from(i).ok())
.or(Some(0));
- (with_retries, without_retries)
+ (with_retries, without_retries, Some(0), Some(0))
}
}
@@ -185,7 +185,14 @@ impl PaymentIntentMetricAccumulator for PaymentsSuccessRateAccumulator {
}
impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator {
- type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
+ type MetricOutput = (
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ );
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) {
self.total_with_retries = match (
@@ -235,6 +242,8 @@ impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator {
count_with_retries,
total_without_retries,
count_without_retries,
+ Some(0),
+ Some(0),
)
}
}
@@ -301,13 +310,19 @@ impl PaymentIntentMetricsAccumulator {
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 (
+ smart_retried_amount,
+ smart_retried_amount_without_smart_retries,
+ smart_retried_amount_in_usd,
+ smart_retried_amount_without_smart_retries_in_usd,
+ ) = self.smart_retried_amount.collect();
let (
payment_processed_amount,
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
+ payment_processed_amount_in_usd,
+ payment_processed_amount_without_smart_retries_in_usd,
) = self.payment_processed_amount.collect();
let (
payments_success_rate_distribution_without_smart_retries,
@@ -317,7 +332,9 @@ impl PaymentIntentMetricsAccumulator {
successful_smart_retries: self.successful_smart_retries.collect(),
total_smart_retries: self.total_smart_retries.collect(),
smart_retried_amount,
+ smart_retried_amount_in_usd,
smart_retried_amount_without_smart_retries,
+ smart_retried_amount_without_smart_retries_in_usd,
payment_intent_count: self.payment_intent_count.collect(),
successful_payments,
successful_payments_without_smart_retries,
@@ -330,6 +347,8 @@ impl PaymentIntentMetricsAccumulator {
payment_processed_count_without_smart_retries,
payments_success_rate_distribution_without_smart_retries,
payments_failure_rate_distribution_without_smart_retries,
+ payment_processed_amount_in_usd,
+ payment_processed_amount_without_smart_retries_in_usd,
}
}
}
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index e04c3b7bd9e..076c28f4f37 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -10,8 +10,10 @@ use api_models::analytics::{
PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse,
SankeyResponse,
};
-use common_enums::IntentStatus;
+use bigdecimal::ToPrimitive;
+use common_enums::{Currency, IntentStatus};
use common_utils::{errors::CustomResult, types::TimeRange};
+use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
@@ -120,6 +122,7 @@ pub async fn get_sankey(
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
+ ex_rates: &ExchangeRates,
auth: &AuthInfo,
req: GetPaymentIntentMetricRequest,
) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> {
@@ -226,16 +229,20 @@ 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_in_usd = 0;
let mut total_smart_retried_amount_without_smart_retries = 0;
+ let mut total_smart_retried_amount_without_smart_retries_in_usd = 0;
let mut total = 0;
let mut total_payment_processed_amount = 0;
+ let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_count = 0;
let mut total_payment_processed_amount_without_smart_retries = 0;
+ let mut total_payment_processed_amount_without_smart_retries_in_usd = 0;
let mut total_payment_processed_count_without_smart_retries = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
- let collected_values = val.collect();
+ let mut collected_values = val.collect();
if let Some(success_count) = collected_values.successful_payments {
success += success_count;
}
@@ -247,20 +254,95 @@ pub async fn get_metrics(
total += total_count;
}
if let Some(retried_amount) = collected_values.smart_retried_amount {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(retried_amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.smart_retried_amount_in_usd = amount_in_usd;
total_smart_retried_amount += retried_amount;
+ total_smart_retried_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(retried_amount) =
collected_values.smart_retried_amount_without_smart_retries
{
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(retried_amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.smart_retried_amount_without_smart_retries_in_usd = amount_in_usd;
total_smart_retried_amount_without_smart_retries += retried_amount;
+ total_smart_retried_amount_without_smart_retries_in_usd +=
+ amount_in_usd.unwrap_or(0);
}
if let Some(amount) = collected_values.payment_processed_amount {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.payment_processed_amount_in_usd = amount_in_usd;
+ total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
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 {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.payment_processed_amount_without_smart_retries_in_usd =
+ amount_in_usd;
+ total_payment_processed_amount_without_smart_retries_in_usd +=
+ amount_in_usd.unwrap_or(0);
total_payment_processed_amount_without_smart_retries += amount;
}
if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
@@ -293,6 +375,14 @@ pub async fn get_metrics(
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
+ total_smart_retried_amount_in_usd: Some(total_smart_retried_amount_in_usd),
+ total_smart_retried_amount_without_smart_retries_in_usd: Some(
+ total_smart_retried_amount_without_smart_retries_in_usd,
+ ),
+ total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd),
+ total_payment_processed_amount_without_smart_retries_in_usd: Some(
+ total_payment_processed_amount_without_smart_retries_in_usd,
+ ),
total_payment_processed_count: Some(total_payment_processed_count),
total_payment_processed_count_without_smart_retries: Some(
total_payment_processed_count_without_smart_retries,
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
index 506965375f5..2ba75ca8519 100644
--- 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
@@ -61,7 +61,7 @@ where
query_builder
.add_select_column("attempt_count == 1 as first_attempt")
.switch()?;
-
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Sum {
field: "amount",
@@ -101,7 +101,10 @@ where
.add_group_by_clause("attempt_count")
.attach_printable("Error grouping by attempt_count")
.switch()?;
-
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by currency")
+ .switch()?;
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
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
index 8105a4c82a4..b92b7356924 100644
--- 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
@@ -63,6 +63,7 @@ where
.add_select_column("attempt_count == 1 as first_attempt")
.switch()?;
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -102,7 +103,10 @@ where
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
-
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by first_attempt")
+ .switch()?;
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
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 8468911f7bb..ac08f59f358 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -62,7 +62,7 @@ where
query_builder
.add_select_column("attempt_count == 1 as first_attempt")
.switch()?;
-
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -102,7 +102,10 @@ where
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
-
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by currency")
+ .switch()?;
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index 4388b2071fe..651eeb0bcfe 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -272,7 +272,14 @@ impl PaymentMetricAccumulator for CountAccumulator {
}
impl PaymentMetricAccumulator for ProcessedAmountAccumulator {
- type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>);
+ type MetricOutput = (
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ Option<u64>,
+ );
#[inline]
fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {
self.total_with_retries = match (
@@ -322,6 +329,8 @@ impl PaymentMetricAccumulator for ProcessedAmountAccumulator {
count_with_retries,
total_without_retries,
count_without_retries,
+ Some(0),
+ Some(0),
)
}
}
@@ -378,6 +387,8 @@ impl PaymentMetricsAccumulator {
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
+ payment_processed_amount_usd,
+ payment_processed_amount_without_smart_retries_usd,
) = self.processed_amount.collect();
let (
payments_success_rate_distribution,
@@ -406,6 +417,8 @@ impl PaymentMetricsAccumulator {
payments_failure_rate_distribution_without_smart_retries,
failure_reason_count,
failure_reason_count_without_smart_retries,
+ payment_processed_amount_usd,
+ payment_processed_amount_without_smart_retries_usd,
}
}
}
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index 59ae549b283..bcd009270dc 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -9,7 +9,10 @@ use api_models::analytics::{
FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse,
PaymentsAnalyticsMetadata, PaymentsMetricsResponse,
};
+use bigdecimal::ToPrimitive;
+use common_enums::Currency;
use common_utils::errors::CustomResult;
+use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
@@ -46,6 +49,7 @@ pub enum TaskType {
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
+ ex_rates: &ExchangeRates,
auth: &AuthInfo,
req: GetPaymentMetricRequest,
) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> {
@@ -224,18 +228,57 @@ pub async fn get_metrics(
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 mut total_payment_processed_amount_usd = 0;
+ let mut total_payment_processed_amount_without_smart_retries_usd = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
- let collected_values = val.collect();
+ let mut collected_values = val.collect();
if let Some(amount) = collected_values.payment_processed_amount {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.payment_processed_amount_usd = amount_in_usd;
total_payment_processed_amount += amount;
+ total_payment_processed_amount_usd += amount_in_usd.unwrap_or(0);
}
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 {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.payment_processed_amount_without_smart_retries_usd = amount_in_usd;
total_payment_processed_amount_without_smart_retries += amount;
+ total_payment_processed_amount_without_smart_retries_usd +=
+ amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count_without_smart_retries {
total_payment_processed_count_without_smart_retries += count;
@@ -252,14 +295,17 @@ pub async fn get_metrics(
}
})
.collect();
-
Ok(PaymentsMetricsResponse {
query_data,
meta_data: [PaymentsAnalyticsMetadata {
total_payment_processed_amount: Some(total_payment_processed_amount),
+ total_payment_processed_amount_usd: Some(total_payment_processed_amount_usd),
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
+ total_payment_processed_amount_without_smart_retries_usd: Some(
+ total_payment_processed_amount_without_smart_retries_usd,
+ ),
total_payment_processed_count: Some(total_payment_processed_count),
total_payment_processed_count_without_smart_retries: Some(
total_payment_processed_count_without_smart_retries,
diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
index b8b3868803c..fa54c173041 100644
--- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs
+++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
@@ -50,6 +50,7 @@ where
alias: Some("total"),
})
.switch()?;
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -79,6 +80,11 @@ where
.switch()?;
}
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by currency")
+ .switch()?;
+
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
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
index 9bc554eaae7..a315b2fc4c8 100644
--- a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs
+++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs
@@ -57,6 +57,8 @@ where
query_builder.add_select_column("first_attempt").switch()?;
+ query_builder.add_select_column("currency").switch()?;
+
query_builder
.add_select_column(Aggregate::Sum {
field: "amount",
@@ -95,6 +97,12 @@ where
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
+
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by currency")
+ .switch()?;
+
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index b95404080b0..8d63bc3096c 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -203,7 +203,9 @@ pub struct AnalyticsMetadata {
#[derive(Debug, serde::Serialize)]
pub struct PaymentsAnalyticsMetadata {
pub total_payment_processed_amount: Option<u64>,
+ pub total_payment_processed_amount_usd: Option<u64>,
pub total_payment_processed_amount_without_smart_retries: Option<u64>,
+ pub total_payment_processed_amount_without_smart_retries_usd: 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>,
@@ -218,6 +220,10 @@ pub struct PaymentIntentsAnalyticsMetadata {
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_smart_retried_amount_in_usd: Option<u64>,
+ pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
+ pub total_payment_processed_amount_in_usd: Option<u64>,
+ pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>,
pub total_payment_processed_count: Option<u64>,
pub total_payment_processed_count_without_smart_retries: Option<u64>,
}
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 41f11c19ef8..05548245e8e 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -223,7 +223,9 @@ 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_in_usd: Option<u64>,
pub smart_retried_amount_without_smart_retries: Option<u64>,
+ pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>,
pub payment_intent_count: Option<u64>,
pub successful_payments: Option<u32>,
pub successful_payments_without_smart_retries: Option<u32>,
@@ -231,8 +233,10 @@ pub struct PaymentIntentMetricsBucketValue {
pub payments_success_rate: Option<f64>,
pub payments_success_rate_without_smart_retries: Option<f64>,
pub payment_processed_amount: Option<u64>,
+ pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
+ pub payment_processed_amount_without_smart_retries_in_usd: 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>,
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index 1120ab092d7..1faba79eb37 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -271,8 +271,10 @@ pub struct PaymentMetricsBucketValue {
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
+ pub payment_processed_amount_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
+ pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub payment_processed_count_without_smart_retries: Option<u64>,
pub avg_ticket_size: Option<f64>,
pub payment_error_message: Option<Vec<ErrorResult>>,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index aa6db56bb34..fead4c720c3 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -32,7 +32,10 @@ pub mod routes {
use crate::{
consts::opensearch::SEARCH_INDEXES,
- core::{api_locking, errors::user::UserErrors, verification::utils},
+ core::{
+ api_locking, currency::get_forex_exchange_rates, errors::user::UserErrors,
+ verification::utils,
+ },
db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload},
routes::AppState,
services::{
@@ -397,7 +400,8 @@ pub mod routes {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
- analytics::payments::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -436,7 +440,8 @@ pub mod routes {
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
- analytics::payments::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -482,7 +487,8 @@ pub mod routes {
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
- analytics::payments::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -523,7 +529,8 @@ pub mod routes {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
- analytics::payment_intents::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -562,7 +569,8 @@ pub mod routes {
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
- analytics::payment_intents::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -608,7 +616,8 @@ pub mod routes {
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
- analytics::payment_intents::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs
index 96d75098271..912484b014a 100644
--- a/crates/router/src/core/currency.rs
+++ b/crates/router/src/core/currency.rs
@@ -1,4 +1,6 @@
+use analytics::errors::AnalyticsError;
use common_utils::errors::CustomResult;
+use currency_conversion::types::ExchangeRates;
use error_stack::ResultExt;
use crate::{
@@ -46,3 +48,19 @@ pub async fn convert_forex(
.change_context(ApiErrorResponse::InternalServerError)?,
))
}
+
+pub async fn get_forex_exchange_rates(
+ state: SessionState,
+) -> CustomResult<ExchangeRates, AnalyticsError> {
+ let forex_api = state.conf.forex_api.get_inner();
+ let rates = get_forex_rates(
+ &state,
+ forex_api.call_delay,
+ forex_api.local_fetch_retry_delay,
+ forex_api.local_fetch_retry_count,
+ )
+ .await
+ .change_context(AnalyticsError::ForexFetchFailed)?;
+
+ Ok((*rates.data).clone())
+}
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs
index dcfe0347d6f..2173478ab67 100644
--- a/crates/router/src/utils/currency.rs
+++ b/crates/router/src/utils/currency.rs
@@ -26,7 +26,7 @@ const FALLBACK_FOREX_API_CURRENCY_PREFIX: &str = "USD";
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FxExchangeRatesCacheEntry {
- data: Arc<ExchangeRates>,
+ pub data: Arc<ExchangeRates>,
timestamp: i64,
}
@@ -421,7 +421,13 @@ pub async fn fallback_fetch_forex_rates(
conversions.insert(enum_curr, currency_factors);
}
None => {
- logger::error!("Rates for {} not received from API", &enum_curr);
+ if enum_curr == enums::Currency::USD {
+ let currency_factors =
+ CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0));
+ conversions.insert(enum_curr, currency_factors);
+ } else {
+ logger::error!("Rates for {} not received from API", &enum_curr);
+ }
}
};
}
|
2024-10-23T19:46:05Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- implemented currency_conversion for calculating values of amount related metrics from their currency (i.e `INR`) to
`USD` and store it in a separate field variant I created `<fieldname>_in_usd`
- Implemented a total_amount_in_usd variant for all the total fields related to amounts in query Metadata
### Fixes #6416
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
The total amount calculated for all payment analytics buckets related to amounts is incorrect because currency conversion is not being applied before summing the values. As a result, amounts in different currencies are being added together, leading to an inaccurate total.
### Dependency
This functionality depends on `currency_conversion` crate directly to fetch exchange rates.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### API request for metrics
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \
--header 'Accept: */*' \
--header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStat' \
--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/130.0.0.0 Safari/537.36' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTgzNzUwNywib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.KlBRpu8DpGZ43u9hsB4xE2oSXNM21HC0RadRdfMe2VI' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-10-13T18:30:00Z",
"endTime": "2024-10-21T12:54:00Z"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"payment_processed_amount"
],
"delta": true
}
]'
```
### API response
```json
{
"queryData": [
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 150000,
"payment_processed_amount_usd": 1782,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_amount_without_smart_retries_usd": 0,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"failure_reason_count": 0,
"failure_reason_count_without_smart_retries": 0,
"currency": "INR",
"status": null,
"connector": null,
"authentication_type": null,
"payment_method": null,
"payment_method_type": null,
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": null,
"time_range": {
"start_time": "2024-10-10T18:30:00.000Z",
"end_time": "2024-10-18T08:24:00.000Z"
},
"time_bucket": "2024-10-10 18:30:00"
},
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 1794006540,
"payment_processed_amount_usd": 1794006540,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_amount_without_smart_retries_usd": 0,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"failure_reason_count": 0,
"failure_reason_count_without_smart_retries": 0,
"currency": "USD",
"status": null,
"connector": null,
"authentication_type": null,
"payment_method": null,
"payment_method_type": null,
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": null,
"time_range": {
"start_time": "2024-10-10T18:30:00.000Z",
"end_time": "2024-10-18T08:24:00.000Z"
},
"time_bucket": "2024-10-10 18:30:00"
},
{
"payment_success_rate": null,
"payment_count": null,
"payment_success_count": null,
"payment_processed_amount": 6540,
"payment_processed_amount_usd": 7118,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_amount_without_smart_retries_usd": 0,
"payment_processed_count_without_smart_retries": null,
"avg_ticket_size": null,
"payment_error_message": null,
"retries_count": null,
"retries_amount_processed": 0,
"connector_success_rate": null,
"payments_success_rate_distribution": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"failure_reason_count": 0,
"failure_reason_count_without_smart_retries": 0,
"currency": "EUR",
"status": null,
"connector": null,
"authentication_type": null,
"payment_method": null,
"payment_method_type": null,
"client_source": null,
"client_version": null,
"profile_id": null,
"card_network": null,
"merchant_id": null,
"card_last_4": null,
"card_issuer": null,
"error_reason": null,
"time_range": {
"start_time": "2024-10-10T18:30:00.000Z",
"end_time": "2024-10-18T08:24:00.000Z"
},
"time_bucket": "2024-10-10 18:30:00"
}
],
"metaData": [
{
"total_payment_processed_amount": 1794163080,
"total_payment_processed_amount_usd": 1794015440,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_amount_without_smart_retries_usd": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0,
"total_failure_reasons_count": 0,
"total_failure_reasons_count_without_smart_retries": 0
}
]
}
```
## Testing for various other scenarios
### by tweaking `development.toml` we can create these scenarios
```toml
[forex_api]
call_delay = 30
local_fetch_retry_count = 5
local_fetch_retry_delay = 1000
api_timeout = 20000
api_key = "YOUR PRIMARY API KEY HER" # set this value to anything else to invalidate it
fallback_api_key = "YOUR FALLBACK API KEY HER" # set this value to anything else to invalidate it
redis_lock_timeout = 2600
```
by setting `call_delay` to 30s we can check for the fetch cycle and redis updates.
1. When primary api isn't working (invalidating the primary api key)
<img width="1722" alt="Screenshot 2024-10-29 at 12 08 11 AM" src="https://github.com/user-attachments/assets/9b5fe452-d339-4dca-b65d-f3fd3e510037">
#### API response : 200
2. when both keys are invalidated
<img width="1709" alt="Screenshot 2024-10-29 at 12 10 32 AM" src="https://github.com/user-attachments/assets/6dcaa6be-236c-40af-b3a1-0d40f789b99c">
<img width="1282" alt="Screenshot 2024-10-29 at 12 32 15 AM" src="https://github.com/user-attachments/assets/0c13bdee-e076-47a7-943b-642765d09804">
#### API response : 500
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
aee11c560e427195a0d321dff19c0d33ec60ba64
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6410
|
Bug: [FEATURE] [PAZE] Add amount, currency and email to paze session response
### Feature Description
Add amount, currency and email to paze session response
### Possible Implementation
{
"wallet_name": "paze",
"client_id": "HIDDEN",
"client_name": "HIDDEN",
"client_profile_id": "HIDDEN",
"transaction_currency_code": "USD",
"transaction_amount": "12.34",
"email_address": "guest@example.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 bd9de3a2962..c85bfad3326 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -16199,7 +16199,9 @@
"required": [
"client_id",
"client_name",
- "client_profile_id"
+ "client_profile_id",
+ "transaction_currency_code",
+ "transaction_amount"
],
"properties": {
"client_id": {
@@ -16213,6 +16215,21 @@
"client_profile_id": {
"type": "string",
"description": "Paze Client Profile ID"
+ },
+ "transaction_currency_code": {
+ "$ref": "#/components/schemas/Currency"
+ },
+ "transaction_amount": {
+ "type": "string",
+ "description": "The transaction amount",
+ "example": "38.02"
+ },
+ "email_address": {
+ "type": "string",
+ "description": "Email Address",
+ "example": "johntest@test.com",
+ "nullable": true,
+ "maxLength": 255
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 61c7911170a..913cb1810ad 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -5578,6 +5578,15 @@ pub struct PazeSessionTokenResponse {
pub client_name: String,
/// Paze Client Profile ID
pub client_profile_id: String,
+ /// The transaction currency code
+ #[schema(value_type = Currency, example = "USD")]
+ pub transaction_currency_code: api_enums::Currency,
+ /// The transaction amount
+ #[schema(value_type = String, example = "38.02")]
+ pub transaction_amount: StringMajorUnit,
+ /// Email Address
+ #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
+ pub email_address: Option<Email>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index d29672058f8..bbeb041e74e 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -816,7 +816,7 @@ pub struct PaymentsSessionData {
pub country: Option<common_enums::CountryAlpha2>,
pub surcharge_details: Option<SurchargeDetails>,
pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
-
+ pub email: Option<pii::Email>,
// Minor Unit amount for amount frame work
pub minor_amount: MinorUnit,
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 736ffdd7b8b..ba8054696a1 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -511,7 +511,13 @@ fn create_paze_session_token(
field_name: "connector_wallets_details".to_string(),
expected_format: "paze_metadata_format".to_string(),
})?;
-
+ let required_amount_type = StringMajorUnitForConnector;
+ let transaction_currency_code = router_data.request.currency;
+ let transaction_amount = required_amount_type
+ .convert(router_data.request.minor_amount, transaction_currency_code)
+ .change_context(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Failed to convert amount to string major unit for paze".to_string(),
+ })?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paze(Box::new(
@@ -519,6 +525,9 @@ fn create_paze_session_token(
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,
+ transaction_currency_code,
+ transaction_amount,
+ email_address: router_data.request.email.clone(),
},
)),
}),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 66e5c996d34..1e3472fc3c1 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2644,6 +2644,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD
),
order_details,
surcharge_details: payment_data.surcharge_details,
+ email: payment_data.email,
})
}
}
@@ -2703,6 +2704,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD
},
),
order_details,
+ email: payment_data.email,
surcharge_details: payment_data.surcharge_details,
})
}
|
2024-10-23T11:22:25Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add amount, currency and email to paze session response
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/6410
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Session Request Paze:
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_id": "pay_Omdaxo733MC34fLvCfYw",
"wallets": [],
"client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h"
}'
```
Response:
```
{
"payment_id": "pay_Omdaxo733MC34fLvCfYw",
"client_secret": "pay_Omdaxo733MC34fLvCfYw_secret_ak2iLU1A5E6PK6XqqY6h",
"session_token": [
{
"wallet_name": "paze",
"client_id": "HIDDEN",
"client_name": "HIDDEN",
"client_profile_id": "HIDDEN",
"transaction_currency_code": "USD",
"transaction_amount": "12.34",
"email_address": "guest@example.com"
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e36ea184ae6d1363fb1af55c790162df9f8b451c
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6406
|
Bug: feat(analytics): remove additional filters from PaymentIntentFilters hotfix
-Additional filters are added to PaymentIntentFilters as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table.
- Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the `Payment Intents` table.
The following additional filters from PaymentIntentFilters should be removed
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index e04c3b7bd9e..af46baed23e 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -371,15 +371,6 @@ 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 25d43e76f03..e81b050214c 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::{AuthenticationType, Currency, IntentStatus};
+use diesel_models::enums::{Currency, IntentStatus};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -54,13 +54,4 @@ 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 8ee9d24b5a0..e9d7f244306 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -34,15 +34,6 @@ 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>,
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 b301a9b9b23..4632cbe9f37 100644
--- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
+++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
@@ -101,15 +101,6 @@ 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
index 07b1bfcf69f..14e168b3523 100644
--- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
+++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
@@ -114,15 +114,6 @@ where
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)?,
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
index 7475a75bb53..644bf35a723 100644
--- 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
@@ -101,15 +101,6 @@ 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/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
index 506965375f5..e7772245063 100644
--- 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
@@ -128,15 +128,6 @@ where
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)?,
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
index 0b55c101a7c..eed6bf85a2c 100644
--- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
@@ -113,15 +113,6 @@ where
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)?,
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
index 8c340d0b2d6..bd1f8bbbcd9 100644
--- 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
@@ -114,15 +114,6 @@ where
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)?,
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
index 8105a4c82a4..6d36aca5172 100644
--- 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
@@ -122,15 +122,6 @@ 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/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
index 0b28cb5366d..bf97e4c41ef 100644
--- 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
@@ -111,15 +111,6 @@ 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/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs
index 20ef8be6277..cea5b2fa465 100644
--- 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
@@ -106,15 +106,6 @@ 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/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
index 8468911f7bb..b23fcafdee0 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -122,15 +122,6 @@ 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 a19bdec518c..4fe5f3a26f5 100644
--- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
@@ -111,15 +111,6 @@ 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 f5539abd9f5..e98efa9f6ab 100644
--- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
@@ -106,15 +106,6 @@ 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/types.rs b/crates/analytics/src/payment_intents/types.rs
index 1a9a2f2ed65..03f2a196c20 100644
--- a/crates/analytics/src/payment_intents/types.rs
+++ b/crates/analytics/src/payment_intents/types.rs
@@ -30,63 +30,6 @@ 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/sqlx.rs b/crates/analytics/src/sqlx.rs
index ae72bbeffea..89eb2ee0bde 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -604,45 +604,6 @@ 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),
@@ -666,15 +627,6 @@ 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,
@@ -700,58 +652,10 @@ 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,
})
}
}
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index fc21bf09819..435e95451fe 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -35,12 +35,6 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> {
PaymentIntentDimensions::PaymentIntentStatus,
PaymentIntentDimensions::Currency,
PaymentIntentDimensions::ProfileId,
- PaymentIntentDimensions::Connector,
- PaymentIntentDimensions::AuthType,
- PaymentIntentDimensions::PaymentMethod,
- PaymentIntentDimensions::PaymentMethodType,
- PaymentIntentDimensions::CardNetwork,
- PaymentIntentDimensions::MerchantId,
]
.into_iter()
.map(Into::into)
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 41f11c19ef8..d018437ae8c 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -6,9 +6,7 @@ use std::{
use common_utils::id_type;
use super::{NameDescription, TimeRange};
-use crate::enums::{
- AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
-};
+use crate::enums::{Currency, IntentStatus};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentIntentFilters {
@@ -18,24 +16,6 @@ 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(
@@ -60,15 +40,6 @@ pub enum PaymentIntentDimensions {
PaymentIntentStatus,
Currency,
ProfileId,
- Connector,
- AuthType,
- PaymentMethod,
- PaymentMethodType,
- CardNetwork,
- MerchantId,
- CardLast4,
- CardIssuer,
- ErrorReason,
}
#[derive(
@@ -138,15 +109,6 @@ 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")]
@@ -160,30 +122,12 @@ 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,
}
@@ -195,15 +139,6 @@ 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);
}
}
|
2024-10-23T07:54:30Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Hotfix PR for: [https://github.com/juspay/hyperswitch/pull/6403](https://github.com/juspay/hyperswitch/pull/6403)
- Additional filters are added to `PaymentIntentFilters` as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table.
- Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the Payment Intents table.
Removed the following additional filters from `PaymentIntentFilters`
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes: [https://github.com/juspay/hyperswitch/issues/6404](https://github.com/juspay/hyperswitch/issues/6406)
Dashboard is raising error (status_code - 500) when payment intent based analytics APIs ae being hit, due to filter fields not present in the payment intents table.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error.
- Hit the curl:
```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/129.0.0.0 Safari/537.36' \
--header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \
--header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-10-14T18:30:00Z",
"endTime": "2024-10-22T15:24:00Z"
},
"groupByNames": [
"currency"
],
"filters": {
"connector": [
"stripe_test"
]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"successful_smart_retries",
"total_smart_retries",
"smart_retried_amount"
]
}
]'
```
- Response:
```bash
{
"queryData": [
{
"successful_smart_retries": 1,
"total_smart_retries": 1,
"smart_retried_amount": 6540,
"smart_retried_amount_without_smart_retries": 0,
"payment_intent_count": null,
"successful_payments": null,
"successful_payments_without_smart_retries": null,
"total_payments": null,
"payments_success_rate": null,
"payments_success_rate_without_smart_retries": null,
"payment_processed_amount": 0,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_count_without_smart_retries": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"status": null,
"currency": "USD",
"profile_id": null,
"time_range": {
"start_time": "2024-10-18T00:00:00.000Z",
"end_time": "2024-10-18T23:00:00.000Z"
},
"time_bucket": "2024-10-18 00:00:00"
}
],
"metaData": [
{
"total_success_rate": null,
"total_success_rate_without_smart_retries": null,
"total_smart_retried_amount": 6540,
"total_smart_retried_amount_without_smart_retries": 0,
"total_payment_processed_amount": 0,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
76dda56642ceef8cc56104a715b76c4c1663da28
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6457
|
Bug: feat(users): add tenant_id in user roles
- Use global interface for user roles
- Add column tenant_id in user_roles
- Handle insertion of tenant_id
- Hadle token validation, a token issued in one tenant should not work in other tenancy
|
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index e2ab676b2d3..782d7f50eac 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1343,6 +1343,8 @@ diesel::table! {
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
+ #[max_length = 64]
+ tenant_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 5651bf95dd9..73d2de8c573 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1289,6 +1289,8 @@ diesel::table! {
#[max_length = 64]
entity_type -> Nullable<Varchar>,
version -> UserRoleVersion,
+ #[max_length = 64]
+ tenant_id -> Varchar,
}
}
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index 71caa41deac..ceddbfd61e4 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -24,6 +24,7 @@ pub struct UserRole {
pub entity_id: Option<String>,
pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
+ pub tenant_id: String,
}
impl UserRole {
@@ -87,6 +88,7 @@ pub struct UserRoleNew {
pub entity_id: Option<String>,
pub entity_type: Option<EntityType>,
pub version: enums::UserRoleVersion,
+ pub tenant_id: String,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index ed25725358a..2c9aec39b04 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -1853,7 +1853,7 @@ pub mod routes {
return Err(OpenSearchError::AccessForbiddenError)?;
}
let user_roles: HashSet<UserRole> = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
org_id: Some(&auth.org_id),
@@ -1976,7 +1976,7 @@ pub mod routes {
return Err(OpenSearchError::AccessForbiddenError)?;
}
let user_roles: HashSet<UserRole> = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &auth.user_id,
org_id: Some(&auth.org_id),
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index df4ce1d8148..5c7b77246e2 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -94,6 +94,8 @@ pub enum UserErrors {
MaxTotpAttemptsReached,
#[error("Maximum attempts reached for Recovery Code")]
MaxRecoveryCodeAttemptsReached,
+ #[error("Forbidden tenant id")]
+ ForbiddenTenantId,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -239,6 +241,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::MaxRecoveryCodeAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None))
}
+ Self::ForbiddenTenantId => {
+ AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None))
+ }
}
}
}
@@ -289,6 +294,7 @@ impl UserErrors {
Self::AuthConfigParsingError => "Auth config parsing error",
Self::SSOFailed => "Invalid SSO request",
Self::JwtProfileIdMissing => "profile_id missing in JWT",
+ Self::ForbiddenTenantId => "Forbidden tenant id",
}
}
}
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs
index ea3459709c6..521c978e3c2 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -94,6 +94,7 @@ pub async fn generate_recon_token(
&state.conf,
user.org_id.clone(),
user.profile_id.clone(),
+ user.tenant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 35b26926ed2..aad2537c3d9 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -598,7 +598,7 @@ async fn handle_existing_user_invitation(
let now = common_utils::date_time::now();
if state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
invitee_user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -614,7 +614,7 @@ async fn handle_existing_user_invitation(
}
if state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
invitee_user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -650,6 +650,10 @@ async fn handle_existing_user_invitation(
EntityType::Organization => {
user_role
.add_entity(domain::OrganizationLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
})
.insert_in_v2(state)
@@ -658,6 +662,10 @@ async fn handle_existing_user_invitation(
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
@@ -671,6 +679,10 @@ async fn handle_existing_user_invitation(
.ok_or(UserErrors::InternalServerError)?;
user_role
.add_entity(domain::ProfileLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: profile_id.clone(),
@@ -777,6 +789,10 @@ async fn handle_new_user_invitation(
EntityType::Organization => {
user_role
.add_entity(domain::OrganizationLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
})
.insert_in_v2(state)
@@ -785,6 +801,10 @@ async fn handle_new_user_invitation(
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
@@ -798,6 +818,10 @@ async fn handle_new_user_invitation(
.ok_or(UserErrors::InternalServerError)?;
user_role
.add_entity(domain::ProfileLevel {
+ tenant_id: user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: profile_id.clone(),
@@ -864,6 +888,7 @@ async fn handle_new_user_invitation(
org_id: user_from_token.org_id.clone(),
role_id: request.role_id.clone(),
profile_id: None,
+ tenant_id: user_from_token.tenant_id.clone(),
};
let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
@@ -909,7 +934,7 @@ pub async fn resend_invite(
.into();
let user_role = match state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user.get_user_id(),
&user_from_token.org_id,
@@ -932,7 +957,7 @@ pub async fn resend_invite(
let user_role = match user_role {
Some(user_role) => user_role,
None => state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user.get_user_id(),
&user_from_token.org_id,
@@ -1102,6 +1127,13 @@ pub async fn create_internal_user(
}
})?;
+ let default_tenant_id = common_utils::consts::DEFAULT_TENANT.to_string();
+
+ if state.tenant.tenant_id != default_tenant_id {
+ return Err(UserErrors::ForbiddenTenantId)
+ .attach_printable("Operation allowed only for the default tenant.");
+ }
+
let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
);
@@ -1142,6 +1174,7 @@ pub async fn create_internal_user(
UserStatus::Active,
)
.add_entity(domain::MerchantLevel {
+ tenant_id: default_tenant_id,
org_id: internal_merchant.organization_id,
merchant_id: internal_merchant_id,
})
@@ -1195,7 +1228,7 @@ pub async fn list_user_roles_details(
}
let user_roles_set = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: required_user.get_user_id(),
org_id: Some(&user_from_token.org_id),
@@ -2372,7 +2405,7 @@ pub async fn list_orgs_for_user(
}
let orgs = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
org_id: None,
@@ -2437,7 +2470,7 @@ pub async fn list_merchants_for_user_in_org(
.change_context(UserErrors::InternalServerError)?,
EntityType::Merchant | EntityType::Profile => {
let merchant_ids = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
org_id: Some(&user_from_token.org_id),
@@ -2516,7 +2549,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(
.change_context(UserErrors::InternalServerError)?,
EntityType::Profile => {
let profile_ids = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
org_id: Some(&user_from_token.org_id),
@@ -2592,7 +2625,7 @@ pub async fn switch_org_for_user(
}
let user_role = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
org_id: Some(&request.org_id),
@@ -2621,6 +2654,7 @@ pub async fn switch_org_for_user(
request.org_id.clone(),
user_role.role_id.clone(),
profile_id.clone(),
+ user_from_token.tenant_id,
)
.await?;
@@ -2764,7 +2798,7 @@ pub async fn switch_merchant_for_user_in_org(
EntityType::Merchant | EntityType::Profile => {
let user_role = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
org_id: Some(&user_from_token.org_id),
@@ -2805,6 +2839,7 @@ pub async fn switch_merchant_for_user_in_org(
org_id.clone(),
role_id.clone(),
profile_id,
+ user_from_token.tenant_id,
)
.await?;
@@ -2879,7 +2914,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
EntityType::Profile => {
let user_role = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload{
user_id:&user_from_token.user_id,
org_id: Some(&user_from_token.org_id),
@@ -2910,6 +2945,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant(
user_from_token.org_id.clone(),
role_id.clone(),
profile_id,
+ user_from_token.tenant_id,
)
.await?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 27c1e2ae494..95a8b7d51d1 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -156,7 +156,7 @@ pub async fn update_user_role(
let mut is_updated = false;
let v2_user_role_to_be_updated = match state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
@@ -210,7 +210,7 @@ pub async fn update_user_role(
}
state
- .store
+ .global_store
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
@@ -229,7 +229,7 @@ pub async fn update_user_role(
}
let v1_user_role_to_be_updated = match state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
@@ -283,7 +283,7 @@ pub async fn update_user_role(
}
state
- .store
+ .global_store
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
&user_from_token.org_id,
@@ -470,7 +470,7 @@ pub async fn delete_user_role(
// Find in V2
let user_role_v2 = match state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -517,7 +517,7 @@ pub async fn delete_user_role(
user_role_deleted_flag = true;
state
- .store
+ .global_store
.delete_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -532,7 +532,7 @@ pub async fn delete_user_role(
// Find in V1
let user_role_v1 = match state
- .store
+ .global_store
.find_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -579,7 +579,7 @@ pub async fn delete_user_role(
user_role_deleted_flag = true;
state
- .store
+ .global_store
.delete_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
&user_from_token.org_id,
@@ -599,7 +599,7 @@ pub async fn delete_user_role(
// Check if user has any more role associations
let remaining_roles = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_db.get_user_id(),
org_id: None,
@@ -780,7 +780,7 @@ pub async fn list_invitations_for_user(
user_from_token: auth::UserIdFromAuth,
) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> {
let user_roles = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
org_id: None,
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 81319ae4c0b..de0c6282fc2 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -123,7 +123,6 @@ pub trait StorageInterface:
+ routing_algorithm::RoutingAlgorithmInterface
+ gsm::GsmInterface
+ unified_translations::UnifiedTranslationsInterface
- + user_role::UserRoleInterface
+ authorization::AuthorizationInterface
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
@@ -144,6 +143,7 @@ pub trait GlobalStorageInterface:
+ Sync
+ dyn_clone::DynClone
+ user::UserInterface
+ + user_role::UserRoleInterface
+ user_key_store::UserKeyStoreInterface
+ 'static
{
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d32c6b254eb..2d9a949879a 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -234,6 +234,7 @@ impl UserRoleInterface for MockDb {
entity_id: None,
entity_type: None,
version: enums::UserRoleVersion::V1,
+ tenant_id: user_role.tenant_id,
};
db_user_roles.push(user_role.clone());
Ok(user_role)
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index cbd694f3acd..b80ade89178 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -179,6 +179,7 @@ pub struct UserFromSinglePurposeToken {
pub user_id: String,
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
+ pub tenant_id: Option<String>,
}
#[cfg(feature = "olap")]
@@ -189,6 +190,7 @@ pub struct SinglePurposeToken {
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
pub exp: u64,
+ pub tenant_id: Option<String>,
}
#[cfg(feature = "olap")]
@@ -199,6 +201,7 @@ impl SinglePurposeToken {
origin: domain::Origin,
settings: &Settings,
path: Vec<TokenPurpose>,
+ tenant_id: Option<String>,
) -> UserResult<String> {
let exp_duration =
std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS);
@@ -209,6 +212,7 @@ impl SinglePurposeToken {
origin,
exp,
path,
+ tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
@@ -222,6 +226,7 @@ pub struct AuthToken {
pub exp: u64,
pub org_id: id_type::OrganizationId,
pub profile_id: Option<id_type::ProfileId>,
+ pub tenant_id: Option<String>,
}
#[cfg(feature = "olap")]
@@ -233,6 +238,7 @@ impl AuthToken {
settings: &Settings,
org_id: id_type::OrganizationId,
profile_id: Option<id_type::ProfileId>,
+ tenant_id: Option<String>,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
@@ -243,6 +249,7 @@ impl AuthToken {
exp,
org_id,
profile_id,
+ tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
@@ -255,6 +262,7 @@ pub struct UserFromToken {
pub role_id: String,
pub org_id: id_type::OrganizationId,
pub profile_id: Option<id_type::ProfileId>,
+ pub tenant_id: Option<String>,
}
pub struct UserIdFromAuth {
@@ -268,6 +276,7 @@ pub struct SinglePurposeOrLoginToken {
pub role_id: Option<String>,
pub purpose: Option<TokenPurpose>,
pub exp: u64,
+ pub tenant_id: Option<String>,
}
pub trait AuthInfo {
@@ -751,6 +760,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
if self.0 != payload.purpose {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
@@ -761,6 +774,7 @@ where
user_id: payload.user_id.clone(),
origin: payload.origin.clone(),
path: payload.path,
+ tenant_id: payload.tenant_id,
},
AuthenticationType::SinglePurposeJwt {
user_id: payload.user_id,
@@ -785,6 +799,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
if self.0 != payload.purpose {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
@@ -795,6 +813,7 @@ where
user_id: payload.user_id.clone(),
origin: payload.origin.clone(),
path: payload.path,
+ tenant_id: payload.tenant_id,
}),
AuthenticationType::SinglePurposeJwt {
user_id: payload.user_id,
@@ -824,6 +843,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let is_purpose_equal = payload
.purpose
@@ -1396,6 +1419,11 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
+
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
@@ -1424,6 +1452,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
@@ -1435,6 +1467,7 @@ where
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
+ tenant_id: payload.tenant_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -1459,6 +1492,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
@@ -1518,6 +1555,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
@@ -1559,6 +1600,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
@@ -1595,6 +1640,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
@@ -1740,6 +1789,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
@@ -1773,6 +1826,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
@@ -1912,6 +1969,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
@@ -1987,6 +2048,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.required_permission, &role_info)?;
@@ -2153,6 +2218,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
@@ -2210,6 +2279,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
@@ -2282,6 +2355,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
@@ -2341,6 +2418,11 @@ where
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
+
Ok((
UserFromToken {
user_id: payload.user_id.clone(),
@@ -2348,6 +2430,7 @@ where
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
+ tenant_id: payload.tenant_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
@@ -2372,6 +2455,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
Ok(((), AuthenticationType::NoAuth))
}
@@ -2389,6 +2476,11 @@ where
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
+
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
@@ -2709,6 +2801,10 @@ where
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
+ authorization::check_tenant(
+ payload.tenant_id.clone(),
+ &state.session_state().tenant.tenant_id,
+ )?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(&self.permission, &role_info)?;
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index fe6ffac6ffc..35a0b159ab2 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -112,6 +112,18 @@ pub fn check_permission(
)
}
+pub fn check_tenant(token_tenant_id: Option<String>, header_tenant_id: &str) -> RouterResult<()> {
+ if let Some(tenant_id) = token_tenant_id {
+ if tenant_id != header_tenant_id {
+ return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!(
+ "Token tenant ID: '{}' does not match Header tenant ID: '{}'",
+ tenant_id, header_tenant_id
+ ));
+ }
+ }
+ Ok(())
+}
+
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index c48fe3320f3..5a881728b07 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -689,7 +689,10 @@ impl NewUser {
let org_user_role = self
.get_no_level_user_role(role_id, user_status)
- .add_entity(OrganizationLevel { org_id });
+ .add_entity(OrganizationLevel {
+ tenant_id: state.tenant.tenant_id.clone(),
+ org_id,
+ });
org_user_role.insert_in_v2(&state).await
}
@@ -1116,17 +1119,20 @@ pub struct NoLevel;
#[derive(Clone)]
pub struct OrganizationLevel {
+ pub tenant_id: String,
pub org_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct MerchantLevel {
+ pub tenant_id: String,
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
}
#[derive(Clone)]
pub struct ProfileLevel {
+ pub tenant_id: String,
pub org_id: id_type::OrganizationId,
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
@@ -1163,6 +1169,7 @@ impl NewUserRole<NoLevel> {
}
pub struct EntityInfo {
+ tenant_id: String,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
@@ -1175,6 +1182,7 @@ impl From<OrganizationLevel> for EntityInfo {
Self {
entity_id: value.org_id.get_string_repr().to_owned(),
entity_type: EntityType::Organization,
+ tenant_id: value.tenant_id,
org_id: value.org_id,
merchant_id: None,
profile_id: None,
@@ -1187,6 +1195,7 @@ impl From<MerchantLevel> for EntityInfo {
Self {
entity_id: value.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
+ tenant_id: value.tenant_id,
org_id: value.org_id,
profile_id: None,
merchant_id: Some(value.merchant_id),
@@ -1199,6 +1208,7 @@ impl From<ProfileLevel> for EntityInfo {
Self {
entity_id: value.profile_id.get_string_repr().to_owned(),
entity_type: EntityType::Profile,
+ tenant_id: value.tenant_id,
org_id: value.org_id,
merchant_id: Some(value.merchant_id),
profile_id: Some(value.profile_id),
@@ -1225,6 +1235,7 @@ where
entity_id: Some(entity.entity_id),
entity_type: Some(entity.entity_type),
version: UserRoleVersion::V2,
+ tenant_id: entity.tenant_id,
}
}
@@ -1234,7 +1245,7 @@ where
let new_v2_role = self.convert_to_new_v2_role(entity.into());
state
- .store
+ .global_store
.insert_user_role(new_v2_role)
.await
.change_context(UserErrors::InternalServerError)
diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs
index 3fc05285ea8..86f10f1ceb7 100644
--- a/crates/router/src/types/domain/user/decision_manager.rs
+++ b/crates/router/src/types/domain/user/decision_manager.rs
@@ -65,7 +65,7 @@ impl SPTFlow {
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
Self::MerchantSelect => Ok(state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user.get_user_id(),
org_id: None,
@@ -93,6 +93,7 @@ impl SPTFlow {
next_flow.origin.clone(),
&state.conf,
next_flow.path.to_vec(),
+ Some(state.tenant.tenant_id.clone()),
)
.await
.map(|token| token.into())
@@ -132,6 +133,7 @@ impl JWTFlow {
.ok_or(report!(UserErrors::InternalServerError))
.attach_printable("org_id not found")?,
Some(profile_id),
+ Some(user_role.tenant_id.clone()),
)
.await
.map(|token| token.into())
@@ -299,7 +301,7 @@ impl NextFlow {
self.user.get_verification_days_left(state)?;
}
let user_role = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: self.user.get_user_id(),
org_id: None,
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 8975519fd97..c4647907ff9 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -92,6 +92,7 @@ pub async fn generate_jwt_auth_token_with_attributes(
org_id: id_type::OrganizationId,
role_id: String,
profile_id: id_type::ProfileId,
+ tenant_id: Option<String>,
) -> UserResult<Secret<String>> {
let token = AuthToken::new_token(
user_id,
@@ -100,6 +101,7 @@ pub async fn generate_jwt_auth_token_with_attributes(
&state.conf,
org_id,
Some(profile_id),
+ tenant_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 6f0d94d2927..aaf313a196e 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -142,7 +142,7 @@ pub async fn update_v1_and_v2_user_roles_in_db(
Result<UserRole, Report<StorageError>>,
) {
let updated_v1_role = state
- .store
+ .global_store
.update_user_role_by_user_id_and_lineage(
user_id,
org_id,
@@ -158,7 +158,7 @@ pub async fn update_v1_and_v2_user_roles_in_db(
});
let updated_v2_role = state
- .store
+ .global_store
.update_user_role_by_user_id_and_lineage(
user_id,
org_id,
@@ -228,7 +228,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
};
let user_roles = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
org_id: Some(&org_id),
@@ -272,7 +272,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
};
let user_roles = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
org_id: None,
@@ -317,7 +317,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite(
};
let user_roles = state
- .store
+ .global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id,
org_id: None,
@@ -407,7 +407,7 @@ pub async fn fetch_user_roles_by_payload(
request_entity_type: Option<EntityType>,
) -> UserResult<HashSet<UserRole>> {
Ok(state
- .store
+ .global_store
.list_user_roles_by_org_id(payload)
.await
.change_context(UserErrors::InternalServerError)?
diff --git a/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql
new file mode 100644
index 00000000000..fb9a32c0767
--- /dev/null
+++ b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE user_roles DROP COLUMN IF EXISTS tenant_id;
\ No newline at end of file
diff --git a/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql
new file mode 100644
index 00000000000..68e75f7f5d8
--- /dev/null
+++ b/migrations/2024-10-26-105654_add_column_tenant_id_to_user_roles/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE user_roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(64) NOT NULL DEFAULT 'public';
|
2024-10-28T21:08:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR includes
- Use of global interface for user roles table
- Add tenant_id column in user_roles table
- Handle user_role insertions with correct value for tenant_id
- Auth Changes: Token validation, token issued in one tenancy should not be valid in other
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding 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 [#6457](https://github.com/juspay/hyperswitch/issues/6457)
## How did you test it?
With the multi -tenancy feature flag enabled, when trying to signup by sending different headers for different tenancies>
```
curl --location 'http://localhost:8080/user/signup?token_only=true' \
--header 'x-tenant-id: test' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "global_test@juspay.in",
"password": "Hyper@123"
}'
```
```
curl --location 'http://localhost:8080/user/signup?token_only=true' \
--header 'x-tenant-id: public' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "global_public@juspay.in",
"password": "Hyper@123"
}'
```
The user role is getting inserted properly, with correct values of tenant_id.
<img width="1473" alt="Screenshot 2024-10-29 at 2 42 08 AM" src="https://github.com/user-attachments/assets/f312adce-b405-4684-8891-16caf324cbb4">
When Trying to use one JWT token with some other header that doesn't match with origin tenancy where it is issued it is authentication part is throwing error. Which is correct.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a5ac69d1a77e772e430df8c4187942de44f23079
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6398
|
Bug: fix(payments): total count issue for card-network filter
To close issue https://github.com/juspay/hyperswitch-cloud/issues/7206
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index fd1286a555e..4fb5aaf28f2 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4585,6 +4585,7 @@ impl PaymentListFilterConstraints {
&& self.payment_method_type.is_none()
&& self.authentication_type.is_none()
&& self.merchant_connector_id.is_none()
+ && self.card_network.is_none()
}
}
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 0627fa0048a..b4854e14923 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -382,6 +382,7 @@ impl PaymentAttempt {
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ card_network: Option<Vec<enums::CardNetwork>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
.count()
@@ -405,6 +406,9 @@ impl PaymentAttempt {
if let Some(merchant_connector_id) = merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
+ if let Some(card_network) = card_network {
+ filter = filter.filter(dsl::card_network.eq_any(card_network))
+ }
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 8ecac77e54e..635c9744c56 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -159,6 +159,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>>,
+ card_network: Option<Vec<storage_enums::CardNetwork>>,
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 fd45c475b6d..c37fd2af109 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3888,6 +3888,7 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
+ constraints.card_network,
merchant.storage_scheme,
)
.await
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 3ef9a2d0376..029a84ad500 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1601,6 +1601,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>>,
+ card_network: Option<Vec<common_enums::CardNetwork>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
self.diesel_store
@@ -1612,6 +1613,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
+ card_network,
storage_scheme,
)
.await
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 121397cdfb9..a0c0a095084 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<common_enums::PaymentMethodType>>,
_authentication_type: Option<Vec<common_enums::AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ _card_network: Option<Vec<storage_enums::CardNetwork>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 5087e28b854..78f5b191635 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -406,6 +406,7 @@ 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>>,
+ card_network: Option<Vec<common_enums::CardNetwork>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
@@ -429,6 +430,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
+ card_network,
)
.await
.map_err(|er| {
@@ -1291,6 +1293,7 @@ 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>>,
+ card_network: Option<Vec<common_enums::CardNetwork>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
@@ -1302,6 +1305,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
+ card_network,
storage_scheme,
)
.await
|
2024-10-22T12:47:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [X] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The total count in the payments response was incorrect when the card-network filter was applied. With this PR, the count will now be accurately filtered as well.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 issues https://github.com/juspay/hyperswitch-cloud/issues/7206
## How did you test 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 'http://localhost:8080/payments/list' \
-H 'authorization: Bearer JWT token' \
-H 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'sec-ch-ua-platform: "macOS"' \
--data-raw '{"offset":0,"limit":50,"start_time":"2024-09-21T18:30:00Z","card_network":["Visa"]}'
```
Response
Lets say the total number of payments are 50 , when you apply filter the total_count and count should come as the filtered number . For Eg: When card-network filter = Visa , then the count = 4 and total_count =4
```
{
"count": 4,
"total_count": 4,
"data": [
{
"payment_id": "test_RoHcgHs3m6ZsJ0Y5MEMU",
"merchant_id": "merchant_1729190909",
"status": "failed",
"amount": 10200,
"net_amount": 10200,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_RoHcgHs3m6ZsJ0Y5MEMU_secret_wQHDmUUPatRIfmY8P8VO",
"created": "2024-10-22T00:08:58.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_RoHcgHs3m6ZsJ0Y5MEMU_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lqOYR8GAg2uTrz5WaqA5",
"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,
"connector_mandate_id": null
},
{
"payment_id": "test_EEe6rS8Mkv2vVDxZWowp",
"merchant_id": "merchant_1729190909",
"status": "succeeded",
"amount": 18600,
"net_amount": 18600,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_EEe6rS8Mkv2vVDxZWowp_secret_fvEF0uo7CYqPOgasFSrQ",
"created": "2024-10-21T02:51:29.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_EEe6rS8Mkv2vVDxZWowp_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lqOYR8GAg2uTrz5WaqA5",
"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,
"connector_mandate_id": null
},
{
"payment_id": "test_46x3ZcQVz6U9RtJitDO4",
"merchant_id": "merchant_1729190909",
"status": "succeeded",
"amount": 18200,
"net_amount": 18200,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_46x3ZcQVz6U9RtJitDO4_secret_hrOArvzAKBpwXvShhHo4",
"created": "2024-10-20T18:06:38.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_46x3ZcQVz6U9RtJitDO4_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lqOYR8GAg2uTrz5WaqA5",
"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,
"connector_mandate_id": null
},
{
"payment_id": "test_pghhoGT9kuPuXf2yopXO",
"merchant_id": "merchant_1729190909",
"status": "succeeded",
"amount": 11800,
"net_amount": 11800,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": "paypal_test",
"client_secret": "test_pghhoGT9kuPuXf2yopXO_secret_R0uu1JcxCBN1UFyMDVal",
"created": "2024-10-16T05:26:35.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_pghhoGT9kuPuXf2yopXO_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lqOYR8GAg2uTrz5WaqA5",
"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,
"connector_mandate_id": null
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
26e0c32f4da5689a1c01fbb456ac008a0b831710
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6404
|
Bug: feat(analytics): remove additional filters from PaymentIntentFilters
-Additional filters are added to PaymentIntentFilters as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table.
- Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the `Payment Intents` table.
The following additional filters from PaymentIntentFilters should be removed
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index e04c3b7bd9e..af46baed23e 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -371,15 +371,6 @@ 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 25d43e76f03..e81b050214c 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::{AuthenticationType, Currency, IntentStatus};
+use diesel_models::enums::{Currency, IntentStatus};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
@@ -54,13 +54,4 @@ 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 8ee9d24b5a0..e9d7f244306 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -34,15 +34,6 @@ 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>,
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 b301a9b9b23..4632cbe9f37 100644
--- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
+++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
@@ -101,15 +101,6 @@ 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
index 07b1bfcf69f..14e168b3523 100644
--- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
+++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
@@ -114,15 +114,6 @@ where
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)?,
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
index 7475a75bb53..644bf35a723 100644
--- 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
@@ -101,15 +101,6 @@ 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/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs
index 506965375f5..e7772245063 100644
--- 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
@@ -128,15 +128,6 @@ where
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)?,
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
index 0b55c101a7c..eed6bf85a2c 100644
--- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
+++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs
@@ -113,15 +113,6 @@ where
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)?,
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
index 8c340d0b2d6..bd1f8bbbcd9 100644
--- 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
@@ -114,15 +114,6 @@ where
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)?,
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
index 8105a4c82a4..6d36aca5172 100644
--- 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
@@ -122,15 +122,6 @@ 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/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs
index 0b28cb5366d..bf97e4c41ef 100644
--- 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
@@ -111,15 +111,6 @@ 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/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs
index 20ef8be6277..cea5b2fa465 100644
--- 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
@@ -106,15 +106,6 @@ 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/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
index 8468911f7bb..b23fcafdee0 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -122,15 +122,6 @@ 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 a19bdec518c..4fe5f3a26f5 100644
--- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
@@ -111,15 +111,6 @@ 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 f5539abd9f5..e98efa9f6ab 100644
--- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
@@ -106,15 +106,6 @@ 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/types.rs b/crates/analytics/src/payment_intents/types.rs
index 1a9a2f2ed65..03f2a196c20 100644
--- a/crates/analytics/src/payment_intents/types.rs
+++ b/crates/analytics/src/payment_intents/types.rs
@@ -30,63 +30,6 @@ 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/sqlx.rs b/crates/analytics/src/sqlx.rs
index ae72bbeffea..89eb2ee0bde 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -604,45 +604,6 @@ 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),
@@ -666,15 +627,6 @@ 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,
@@ -700,58 +652,10 @@ 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,
})
}
}
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index fc21bf09819..435e95451fe 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -35,12 +35,6 @@ pub fn get_payment_intent_dimensions() -> Vec<NameDescription> {
PaymentIntentDimensions::PaymentIntentStatus,
PaymentIntentDimensions::Currency,
PaymentIntentDimensions::ProfileId,
- PaymentIntentDimensions::Connector,
- PaymentIntentDimensions::AuthType,
- PaymentIntentDimensions::PaymentMethod,
- PaymentIntentDimensions::PaymentMethodType,
- PaymentIntentDimensions::CardNetwork,
- PaymentIntentDimensions::MerchantId,
]
.into_iter()
.map(Into::into)
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index 41f11c19ef8..d018437ae8c 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -6,9 +6,7 @@ use std::{
use common_utils::id_type;
use super::{NameDescription, TimeRange};
-use crate::enums::{
- AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType,
-};
+use crate::enums::{Currency, IntentStatus};
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct PaymentIntentFilters {
@@ -18,24 +16,6 @@ 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(
@@ -60,15 +40,6 @@ pub enum PaymentIntentDimensions {
PaymentIntentStatus,
Currency,
ProfileId,
- Connector,
- AuthType,
- PaymentMethod,
- PaymentMethodType,
- CardNetwork,
- MerchantId,
- CardLast4,
- CardIssuer,
- ErrorReason,
}
#[derive(
@@ -138,15 +109,6 @@ 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")]
@@ -160,30 +122,12 @@ 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,
}
@@ -195,15 +139,6 @@ 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);
}
}
|
2024-10-22T18:22:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Fix for this PR: [https://github.com/juspay/hyperswitch/pull/5870](https://github.com/juspay/hyperswitch/pull/5870)
- Additional filters are added to `PaymentIntentFilters` as new analytics APIs are expected to be calculated from `Sessionizer Payment Intents` table.
- Existing metrics on current dashboard are breaking due to these new filters as the fields are not present in the Payment Intents table.
Removed the following additional filters from `PaymentIntentFilters`
- connector
- authentication_type
- payment_method
- payment_method_type
- card_network
- merchant_id
- card_last_4
- card_issuer
- error_reason
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Dashboard is raising error (status_code - 500) when payment intent based analytics APIs ae being hit, due to filter fields not present in the payment intents table.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Added filters of connector, payment_method, etc on the dashboard and the payments v2 APIs should not return 500 error.
- Hit the curl:
```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/129.0.0.0 Safari/537.36' \
--header 'api-key: snd_ug3Xjm7pNJ6u3SeC5jQCApLIPr6NdDppvEKht091zd62EJJ0pWF6KziALr0yQEuF' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTc0ODc1Mywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.-NHlfMrAjUDwjMpCo9PAn86koRkkPMBygNfCTh2jiTw' \
--header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-10-14T18:30:00Z",
"endTime": "2024-10-22T15:24:00Z"
},
"groupByNames": [
"currency"
],
"filters": {
"connector": [
"stripe_test"
]
},
"timeSeries": {
"granularity": "G_ONEDAY"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"successful_smart_retries",
"total_smart_retries",
"smart_retried_amount"
]
}
]'
```
- Response:
```bash
{
"queryData": [
{
"successful_smart_retries": 1,
"total_smart_retries": 1,
"smart_retried_amount": 6540,
"smart_retried_amount_without_smart_retries": 0,
"payment_intent_count": null,
"successful_payments": null,
"successful_payments_without_smart_retries": null,
"total_payments": null,
"payments_success_rate": null,
"payments_success_rate_without_smart_retries": null,
"payment_processed_amount": 0,
"payment_processed_count": null,
"payment_processed_amount_without_smart_retries": 0,
"payment_processed_count_without_smart_retries": null,
"payments_success_rate_distribution_without_smart_retries": null,
"payments_failure_rate_distribution_without_smart_retries": null,
"status": null,
"currency": "USD",
"profile_id": null,
"time_range": {
"start_time": "2024-10-18T00:00:00.000Z",
"end_time": "2024-10-18T23:00:00.000Z"
},
"time_bucket": "2024-10-18 00:00:00"
}
],
"metaData": [
{
"total_success_rate": null,
"total_success_rate_without_smart_retries": null,
"total_smart_retried_amount": 6540,
"total_smart_retried_amount_without_smart_retries": 0,
"total_payment_processed_amount": 0,
"total_payment_processed_amount_without_smart_retries": 0,
"total_payment_processed_count": 0,
"total_payment_processed_count_without_smart_retries": 0
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6417
|
Bug: feat(analytics): add `sessionized_metrics` for refunds (backwards compatibility) and `currency_conversion`
## Current Behaviour
- There is no `sessionized_metrics` module for refunds like there is for `payments` and `payment_intents`
- Update the existing metrics with `currency_conversion` usage.
## Proposed Changes
- create `sessionized_metrics` module for refunds
- implement `currency_conversion` for refunds analytics
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index 7ea8e9007f7..b242b3dae81 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -69,11 +69,21 @@ pub async fn get_sankey(
i.refunds_status.unwrap_or_default().as_ref(),
i.attempt_count,
) {
+ (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, 1) => {
+ sankey_response.refunded += i.count;
+ sankey_response.normal_success += i.count
+ }
+ (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, 1) => {
+ sankey_response.partial_refunded += i.count;
+ sankey_response.normal_success += i.count
+ }
(IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => {
- sankey_response.refunded += i.count
+ sankey_response.refunded += i.count;
+ sankey_response.smart_retried_success += i.count
}
(IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => {
- sankey_response.partial_refunded += i.count
+ sankey_response.partial_refunded += i.count;
+ sankey_response.smart_retried_success += i.count
}
(
IntentStatus::Succeeded
diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs
index 651eeb0bcfe..5ca9fdf7516 100644
--- a/crates/analytics/src/payments/accumulator.rs
+++ b/crates/analytics/src/payments/accumulator.rs
@@ -387,7 +387,7 @@ impl PaymentMetricsAccumulator {
payment_processed_count,
payment_processed_amount_without_smart_retries,
payment_processed_count_without_smart_retries,
- payment_processed_amount_usd,
+ payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_usd,
) = self.processed_amount.collect();
let (
@@ -417,7 +417,7 @@ impl PaymentMetricsAccumulator {
payments_failure_rate_distribution_without_smart_retries,
failure_reason_count,
failure_reason_count_without_smart_retries,
- payment_processed_amount_usd,
+ payment_processed_amount_in_usd,
payment_processed_amount_without_smart_retries_usd,
}
}
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index bcd009270dc..01a3b1abc15 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -228,7 +228,7 @@ pub async fn get_metrics(
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 mut total_payment_processed_amount_usd = 0;
+ let mut total_payment_processed_amount_in_usd = 0;
let mut total_payment_processed_amount_without_smart_retries_usd = 0;
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
@@ -251,9 +251,9 @@ pub async fn get_metrics(
})
.map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
.unwrap_or_default();
- collected_values.payment_processed_amount_usd = amount_in_usd;
+ collected_values.payment_processed_amount_in_usd = amount_in_usd;
total_payment_processed_amount += amount;
- total_payment_processed_amount_usd += amount_in_usd.unwrap_or(0);
+ total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
}
if let Some(count) = collected_values.payment_processed_count {
total_payment_processed_count += count;
@@ -299,7 +299,7 @@ pub async fn get_metrics(
query_data,
meta_data: [PaymentsAnalyticsMetadata {
total_payment_processed_amount: Some(total_payment_processed_amount),
- total_payment_processed_amount_usd: Some(total_payment_processed_amount_usd),
+ total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd),
total_payment_processed_amount_without_smart_retries: Some(
total_payment_processed_amount_without_smart_retries,
),
diff --git a/crates/analytics/src/refunds/accumulator.rs b/crates/analytics/src/refunds/accumulator.rs
index 9c51defdcf9..add38c98162 100644
--- a/crates/analytics/src/refunds/accumulator.rs
+++ b/crates/analytics/src/refunds/accumulator.rs
@@ -7,7 +7,7 @@ pub struct RefundMetricsAccumulator {
pub refund_success_rate: SuccessRateAccumulator,
pub refund_count: CountAccumulator,
pub refund_success: CountAccumulator,
- pub processed_amount: SumAccumulator,
+ pub processed_amount: PaymentProcessedAmountAccumulator,
}
#[derive(Debug, Default)]
@@ -22,7 +22,7 @@ pub struct CountAccumulator {
}
#[derive(Debug, Default)]
#[repr(transparent)]
-pub struct SumAccumulator {
+pub struct PaymentProcessedAmountAccumulator {
pub total: Option<i64>,
}
@@ -50,8 +50,8 @@ impl RefundMetricAccumulator for CountAccumulator {
}
}
-impl RefundMetricAccumulator for SumAccumulator {
- type MetricOutput = Option<u64>;
+impl RefundMetricAccumulator for PaymentProcessedAmountAccumulator {
+ type MetricOutput = (Option<u64>, Option<u64>);
#[inline]
fn add_metrics_bucket(&mut self, metrics: &RefundMetricRow) {
self.total = match (
@@ -68,7 +68,7 @@ impl RefundMetricAccumulator for SumAccumulator {
}
#[inline]
fn collect(self) -> Self::MetricOutput {
- self.total.and_then(|i| u64::try_from(i).ok())
+ (self.total.and_then(|i| u64::try_from(i).ok()), Some(0))
}
}
@@ -98,11 +98,14 @@ impl RefundMetricAccumulator for SuccessRateAccumulator {
impl RefundMetricsAccumulator {
pub fn collect(self) -> RefundMetricsBucketValue {
+ let (refund_processed_amount, refund_processed_amount_in_usd) =
+ self.processed_amount.collect();
RefundMetricsBucketValue {
refund_success_rate: self.refund_success_rate.collect(),
refund_count: self.refund_count.collect(),
refund_success_count: self.refund_success.collect(),
- refund_processed_amount: self.processed_amount.collect(),
+ refund_processed_amount,
+ refund_processed_amount_in_usd,
}
}
}
diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs
index 9c4770c79ee..e3bfa4da9d1 100644
--- a/crates/analytics/src/refunds/core.rs
+++ b/crates/analytics/src/refunds/core.rs
@@ -5,9 +5,12 @@ use api_models::analytics::{
refunds::{
RefundDimensions, RefundMetrics, RefundMetricsBucketIdentifier, RefundMetricsBucketResponse,
},
- AnalyticsMetadata, GetRefundFilterRequest, GetRefundMetricRequest, MetricsResponse,
- RefundFilterValue, RefundFiltersResponse,
+ GetRefundFilterRequest, GetRefundMetricRequest, RefundFilterValue, RefundFiltersResponse,
+ RefundsAnalyticsMetadata, RefundsMetricsResponse,
};
+use bigdecimal::ToPrimitive;
+use common_enums::Currency;
+use currency_conversion::{conversion::convert, types::ExchangeRates};
use error_stack::ResultExt;
use router_env::{
logger,
@@ -29,9 +32,10 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
+ ex_rates: &ExchangeRates,
auth: &AuthInfo,
req: GetRefundMetricRequest,
-) -> AnalyticsResult<MetricsResponse<RefundMetricsBucketResponse>> {
+) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> =
HashMap::new();
let mut set = tokio::task::JoinSet::new();
@@ -86,16 +90,20 @@ 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 {
- RefundMetrics::RefundSuccessRate => metrics_builder
- .refund_success_rate
- .add_metrics_bucket(&value),
- RefundMetrics::RefundCount => {
+ RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => {
+ metrics_builder
+ .refund_success_rate
+ .add_metrics_bucket(&value)
+ }
+ RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => {
metrics_builder.refund_count.add_metrics_bucket(&value)
}
- RefundMetrics::RefundSuccessCount => {
+ RefundMetrics::RefundSuccessCount
+ | RefundMetrics::SessionizedRefundSuccessCount => {
metrics_builder.refund_success.add_metrics_bucket(&value)
}
- RefundMetrics::RefundProcessedAmount => {
+ RefundMetrics::RefundProcessedAmount
+ | RefundMetrics::SessionizedRefundProcessedAmount => {
metrics_builder.processed_amount.add_metrics_bucket(&value)
}
}
@@ -107,18 +115,45 @@ pub async fn get_metrics(
metrics_accumulator
);
}
+ let mut total_refund_processed_amount = 0;
+ let mut total_refund_processed_amount_in_usd = 0;
let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator
.into_iter()
- .map(|(id, val)| RefundMetricsBucketResponse {
- values: val.collect(),
- dimensions: id,
+ .map(|(id, val)| {
+ let mut collected_values = val.collect();
+ if let Some(amount) = collected_values.refund_processed_amount {
+ let amount_in_usd = id
+ .currency
+ .and_then(|currency| {
+ i64::try_from(amount)
+ .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e))
+ .ok()
+ .and_then(|amount_i64| {
+ convert(ex_rates, currency, Currency::USD, amount_i64)
+ .inspect_err(|e| {
+ logger::error!("Currency conversion error: {:?}", e)
+ })
+ .ok()
+ })
+ })
+ .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64())
+ .unwrap_or_default();
+ collected_values.refund_processed_amount_in_usd = amount_in_usd;
+ total_refund_processed_amount += amount;
+ total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0);
+ }
+ RefundMetricsBucketResponse {
+ values: collected_values,
+ dimensions: id,
+ }
})
.collect();
- Ok(MetricsResponse {
+ Ok(RefundsMetricsResponse {
query_data,
- meta_data: [AnalyticsMetadata {
- current_time_range: req.time_range,
+ meta_data: [RefundsAnalyticsMetadata {
+ total_refund_processed_amount: Some(total_refund_processed_amount),
+ total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd),
}],
})
}
diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs
index 6ecfd8aeb29..c211ea82d7a 100644
--- a/crates/analytics/src/refunds/metrics.rs
+++ b/crates/analytics/src/refunds/metrics.rs
@@ -10,6 +10,7 @@ mod refund_count;
mod refund_processed_amount;
mod refund_success_count;
mod refund_success_rate;
+mod sessionized_metrics;
use std::collections::HashSet;
use refund_count::RefundCount;
@@ -101,6 +102,26 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::SessionizedRefundSuccessRate => {
+ sessionized_metrics::RefundSuccessRate::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundCount => {
+ sessionized_metrics::RefundCount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundSuccessCount => {
+ sessionized_metrics::RefundSuccessCount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
+ Self::SessionizedRefundProcessedAmount => {
+ sessionized_metrics::RefundProcessedAmount::default()
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
}
}
}
diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
index f0f51a21fe0..6cba5f58fed 100644
--- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
+++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
@@ -52,6 +52,7 @@ where
alias: Some("total"),
})
.switch()?;
+ query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
@@ -78,6 +79,7 @@ where
query_builder.add_group_by_clause(dim).switch()?;
}
+ query_builder.add_group_by_clause("currency").switch()?;
if let Some(granularity) = granularity.as_ref() {
granularity
.set_group_by_clause(&mut query_builder)
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs
new file mode 100644
index 00000000000..bb404cd3410
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs
@@ -0,0 +1,11 @@
+mod refund_count;
+mod refund_processed_amount;
+mod refund_success_count;
+mod refund_success_rate;
+
+pub(super) use refund_count::RefundCount;
+pub(super) use refund_processed_amount::RefundProcessedAmount;
+pub(super) use refund_success_count::RefundSuccessCount;
+pub(super) use refund_success_rate::RefundSuccessRate;
+
+pub use super::{RefundMetric, RefundMetricAnalytics, RefundMetricRow};
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
new file mode 100644
index 00000000000..c77e1f7a52c
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_count.rs
@@ -0,0 +1,120 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundCount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundCount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ 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::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ i.refund_status.as_ref().map(|i| i.0.to_string()),
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.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/refunds/metrics/sessionized_metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
new file mode 100644
index 00000000000..c91938228af
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_processed_amount.rs
@@ -0,0 +1,129 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct RefundProcessedAmount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundProcessedAmount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> =
+ QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "refund_amount",
+ alias: Some("total"),
+ })
+ .switch()?;
+ query_builder.add_select_column("currency").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).switch()?;
+ }
+
+ query_builder.add_group_by_clause("currency").switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Success,
+ )
+ .switch()?;
+
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.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/refunds/metrics/sessionized_metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
new file mode 100644
index 00000000000..332261a3208
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_count.rs
@@ -0,0 +1,125 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums as storage_enums;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(crate) struct RefundSuccessCount {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundSuccessCount
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+
+ 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).switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause(
+ RefundDimensions::RefundStatus,
+ storage_enums::RefundStatus::Success,
+ )
+ .switch()?;
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
new file mode 100644
index 00000000000..35ee0d61b50
--- /dev/null
+++ b/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs
@@ -0,0 +1,120 @@
+use std::collections::HashSet;
+
+use api_models::analytics::{
+ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::RefundMetricRow;
+use crate::{
+ enums::AuthInfo,
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(crate) struct RefundSuccessRate {}
+
+#[async_trait::async_trait]
+impl<T> super::RefundMetric<T> for RefundSuccessRate
+where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ 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: &[RefundDimensions],
+ auth: &AuthInfo,
+ filters: &RefundFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::RefundMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized);
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(RefundDimensions::RefundStatus);
+
+ 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).switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<RefundMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ RefundMetricsBucketIdentifier::new(
+ i.currency.as_ref().map(|i| i.0),
+ None,
+ i.connector.clone(),
+ i.refund_type.as_ref().map(|i| i.0.to_string()),
+ i.profile_id.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 8d63bc3096c..70c0e0e78dc 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -203,7 +203,7 @@ pub struct AnalyticsMetadata {
#[derive(Debug, serde::Serialize)]
pub struct PaymentsAnalyticsMetadata {
pub total_payment_processed_amount: Option<u64>,
- pub total_payment_processed_amount_usd: Option<u64>,
+ pub total_payment_processed_amount_in_usd: Option<u64>,
pub total_payment_processed_amount_without_smart_retries: Option<u64>,
pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>,
pub total_payment_processed_count: Option<u64>,
@@ -228,6 +228,11 @@ pub struct PaymentIntentsAnalyticsMetadata {
pub total_payment_processed_count_without_smart_retries: Option<u64>,
}
+#[derive(Debug, serde::Serialize)]
+pub struct RefundsAnalyticsMetadata {
+ pub total_refund_processed_amount: Option<u64>,
+ pub total_refund_processed_amount_in_usd: Option<u64>,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPaymentFiltersRequest {
@@ -362,6 +367,12 @@ pub struct PaymentIntentsMetricsResponse<T> {
pub meta_data: [PaymentIntentsAnalyticsMetadata; 1],
}
+#[derive(Debug, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RefundsMetricsResponse<T> {
+ pub query_data: Vec<T>,
+ pub meta_data: [RefundsAnalyticsMetadata; 1],
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetApiEventFiltersRequest {
diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs
index 1faba79eb37..b34f8c9293c 100644
--- a/crates/api_models/src/analytics/payments.rs
+++ b/crates/api_models/src/analytics/payments.rs
@@ -271,7 +271,7 @@ pub struct PaymentMetricsBucketValue {
pub payment_count: Option<u64>,
pub payment_success_count: Option<u64>,
pub payment_processed_amount: Option<u64>,
- pub payment_processed_amount_usd: Option<u64>,
+ pub payment_processed_amount_in_usd: Option<u64>,
pub payment_processed_count: Option<u64>,
pub payment_processed_amount_without_smart_retries: Option<u64>,
pub payment_processed_amount_without_smart_retries_usd: Option<u64>,
diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs
index ef17387d1ea..d981bd4382f 100644
--- a/crates/api_models/src/analytics/refunds.rs
+++ b/crates/api_models/src/analytics/refunds.rs
@@ -88,6 +88,10 @@ pub enum RefundMetrics {
RefundCount,
RefundSuccessCount,
RefundProcessedAmount,
+ SessionizedRefundSuccessRate,
+ SessionizedRefundCount,
+ SessionizedRefundSuccessCount,
+ SessionizedRefundProcessedAmount,
}
pub mod metric_behaviour {
@@ -176,6 +180,7 @@ pub struct RefundMetricsBucketValue {
pub refund_count: Option<u64>,
pub refund_success_count: Option<u64>,
pub refund_processed_amount: Option<u64>,
+ pub refund_processed_amount_in_usd: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct RefundMetricsBucketResponse {
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 7272abffbff..77d8cb117ef 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -168,6 +168,11 @@ impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> {
}
}
+impl<T> ApiEventMetric for RefundsMetricsResponse<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 aba1c2e2efa..fc45e3f80e6 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -652,7 +652,8 @@ pub mod routes {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -690,7 +691,8 @@ pub mod routes {
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
@@ -735,7 +737,8 @@ pub mod routes {
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
- analytics::refunds::get_metrics(&state.pool, &auth, req)
+ let ex_rates = get_forex_exchange_rates(state.clone()).await?;
+ analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
|
2024-10-23T19:59:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Add sessionized metrics module and implement backwards compatibility.
- Implement currency conversion for refunds analytics
### Minor unrelated changes
- refactor inconsistent naming of fields in some places => [commit](https://github.com/juspay/hyperswitch/pull/6419/commits/08e53d63b5561163712bdfaefebed1caecdb793b)
- fix sankey incorrect formula => [commit](https://github.com/juspay/hyperswitch/pull/6419/commits/6ae2fb68290bf91a6d10178aa620893c3fd45846)
### Fixes #6417
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Refund metrics didn't had a `sessionized_metrics` module and implementation as were there in payments and payment_intents metrics
- Refund metrics weren't implementing currency conversion.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```bash
curl --location 'http://localhost:8080/analytics/v1/org/metrics/refunds' \
--header 'Accept: */*' \
--header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/json' \
--header 'Origin: http://localhost:9000' \
--header 'QueryType: SingleStat' \
--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/130.0.0.0 Safari/537.36' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '[
{
"timeRange": {
"startTime": "2024-10-15T18:30:00Z",
"endTime": "2024-11-07T09:30:00Z"
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"sessionized_refund_processed_amount"
],
"delta": true
}
]'
```
<img width="750" alt="Screenshot 2024-11-07 at 2 56 08 PM" src="https://github.com/user-attachments/assets/6f5ba9b3-1b41-498f-a685-b1e8bf30f78d">
### For sankey changes
```bash
curl --location 'http://localhost:8080/analytics/v1/profile/metrics/sankey' \
--header 'accept: */*' \
--header 'accept-language: en-US,en;q=0.9' \
--header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMTA4ODY3NSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSJ9.S0OBbdBmFjnRC-1hP-QTVA2fzQESHIvou_8dtmFDCgY' \
--header 'content-type: application/json' \
--header 'origin: https://integ.hyperswitch.io' \
--header 'priority: u=1, i' \
--header 'referer: https://integ.hyperswitch.io/dashboard/new-analytics-payment' \
--header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--header 'sec-fetch-dest: empty' \
--header 'sec-fetch-mode: cors' \
--header 'sec-fetch-site: same-origin' \
--header 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36' \
--data '{"startTime":"2024-10-30T18:30:00Z","endTime":"2024-11-08T11:16:00Z"}'
```
<img width="537" alt="Screenshot 2024-11-08 at 3 03 12 PM" src="https://github.com/user-attachments/assets/1fb56fd2-1585-4423-84dd-3883cc3dfc63">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1ba3d84df1e93d2286db1a262c4a67b3861b90c0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6395
|
Bug: [FEATURE] add payments get-intent API for v2
# Feature Description
Add payments `get-intent` API for v2
|
diff --git a/api-reference-v2/api-reference/payments/payments--get-intent.mdx b/api-reference-v2/api-reference/payments/payments--get-intent.mdx
new file mode 100644
index 00000000000..cd1321be217
--- /dev/null
+++ b/api-reference-v2/api-reference/payments/payments--get-intent.mdx
@@ -0,0 +1,3 @@
+---
+openapi: get /v2/payments/{id}/get-intent
+---
\ No newline at end of file
diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json
index 974e530f311..17dd6dfb7ff 100644
--- a/api-reference-v2/mint.json
+++ b/api-reference-v2/mint.json
@@ -38,6 +38,7 @@
"group": "Payments",
"pages": [
"api-reference/payments/payments--create-intent",
+ "api-reference/payments/payments--get-intent",
"api-reference/payments/payments--session-token",
"api-reference/payments/payments--confirm-intent"
]
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index bd9de3a2962..bb52eb23938 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -1832,7 +1832,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/PaymentsCreateIntentResponse"
+ "$ref": "#/components/schemas/PaymentsIntentResponse"
}
}
}
@@ -1848,6 +1848,47 @@
]
}
},
+ "/v2/payments/{id}/get-intent": {
+ "get": {
+ "tags": [
+ "Payments"
+ ],
+ "summary": "Payments - Get Intent",
+ "description": "**Get a payment intent object when id is passed in path**\n\nYou will require the 'API - Key' from the Hyperswitch dashboard to make the call.",
+ "operationId": "Get the Payment Intent details",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Intent",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Payment Intent",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentsIntentResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payment Intent not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/v2/payments/{id}/confirm-intent": {
"post": {
"tags": [
@@ -13567,179 +13608,6 @@
},
"additionalProperties": false
},
- "PaymentsCreateIntentResponse": {
- "type": "object",
- "required": [
- "id",
- "amount_details",
- "client_secret",
- "capture_method",
- "authentication_type",
- "customer_present",
- "setup_future_usage",
- "apply_mit_exemption",
- "payment_link_enabled",
- "request_incremental_authorization",
- "expires_on",
- "request_external_three_ds_authentication"
- ],
- "properties": {
- "id": {
- "type": "string",
- "description": "Global Payment Id for the payment"
- },
- "amount_details": {
- "$ref": "#/components/schemas/AmountDetailsResponse"
- },
- "client_secret": {
- "type": "string",
- "description": "It's a token used for client side verification.",
- "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"
- },
- "merchant_reference_id": {
- "type": "string",
- "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant.",
- "example": "pay_mbabizu24mvu3mela5njyhpit4",
- "nullable": true,
- "maxLength": 30,
- "minLength": 30
- },
- "routing_algorithm_id": {
- "type": "string",
- "description": "The routing algorithm id to be used for the payment",
- "nullable": true
- },
- "capture_method": {
- "$ref": "#/components/schemas/CaptureMethod"
- },
- "authentication_type": {
- "allOf": [
- {
- "$ref": "#/components/schemas/AuthenticationType"
- }
- ],
- "default": "no_three_ds"
- },
- "billing": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Address"
- }
- ],
- "nullable": true
- },
- "shipping": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Address"
- }
- ],
- "nullable": true
- },
- "customer_id": {
- "type": "string",
- "description": "The identifier for the customer",
- "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
- "nullable": true,
- "maxLength": 64,
- "minLength": 1
- },
- "customer_present": {
- "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment"
- },
- "description": {
- "type": "string",
- "description": "A description for the payment",
- "example": "It's my first payment request",
- "nullable": true
- },
- "return_url": {
- "type": "string",
- "description": "The URL to which you want the user to be redirected after the completion of the payment operation",
- "example": "https://hyperswitch.io",
- "nullable": true
- },
- "setup_future_usage": {
- "$ref": "#/components/schemas/FutureUsage"
- },
- "apply_mit_exemption": {
- "$ref": "#/components/schemas/MitExemptionRequest"
- },
- "statement_descriptor": {
- "type": "string",
- "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.",
- "example": "Hyperswitch Router",
- "nullable": true,
- "maxLength": 22
- },
- "order_details": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/OrderDetailsWithAmount"
- },
- "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount",
- "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]",
- "nullable": true
- },
- "allowed_payment_method_types": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/PaymentMethodType"
- },
- "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent",
- "nullable": true
- },
- "metadata": {
- "type": "object",
- "description": "Metadata is useful for storing additional, unstructured information on an object.",
- "nullable": true
- },
- "connector_metadata": {
- "allOf": [
- {
- "$ref": "#/components/schemas/ConnectorMetadata"
- }
- ],
- "nullable": true
- },
- "feature_metadata": {
- "allOf": [
- {
- "$ref": "#/components/schemas/FeatureMetadata"
- }
- ],
- "nullable": true
- },
- "payment_link_enabled": {
- "$ref": "#/components/schemas/EnablePaymentLinkRequest"
- },
- "payment_link_config": {
- "allOf": [
- {
- "$ref": "#/components/schemas/PaymentLinkConfigRequest"
- }
- ],
- "nullable": true
- },
- "request_incremental_authorization": {
- "$ref": "#/components/schemas/RequestIncrementalAuthorization"
- },
- "expires_on": {
- "type": "string",
- "format": "date-time",
- "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds"
- },
- "frm_metadata": {
- "type": "object",
- "description": "Additional data related to some frm(Fraud Risk Management) connectors",
- "nullable": true
- },
- "request_external_three_ds_authentication": {
- "$ref": "#/components/schemas/External3dsAuthenticationRequest"
- }
- },
- "additionalProperties": false
- },
"PaymentsCreateResponseOpenApi": {
"type": "object",
"required": [
@@ -14433,6 +14301,179 @@
}
}
},
+ "PaymentsIntentResponse": {
+ "type": "object",
+ "required": [
+ "id",
+ "amount_details",
+ "client_secret",
+ "capture_method",
+ "authentication_type",
+ "customer_present",
+ "setup_future_usage",
+ "apply_mit_exemption",
+ "payment_link_enabled",
+ "request_incremental_authorization",
+ "expires_on",
+ "request_external_three_ds_authentication"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Global Payment Id for the payment"
+ },
+ "amount_details": {
+ "$ref": "#/components/schemas/AmountDetailsResponse"
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "It's a token used for client side verification.",
+ "example": "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo"
+ },
+ "merchant_reference_id": {
+ "type": "string",
+ "description": "Unique identifier for the payment. This ensures idempotency for multiple payments\nthat have been done by a single merchant.",
+ "example": "pay_mbabizu24mvu3mela5njyhpit4",
+ "nullable": true,
+ "maxLength": 30,
+ "minLength": 30
+ },
+ "routing_algorithm_id": {
+ "type": "string",
+ "description": "The routing algorithm id to be used for the payment",
+ "nullable": true
+ },
+ "capture_method": {
+ "$ref": "#/components/schemas/CaptureMethod"
+ },
+ "authentication_type": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AuthenticationType"
+ }
+ ],
+ "default": "no_three_ds"
+ },
+ "billing": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "shipping": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "customer_id": {
+ "type": "string",
+ "description": "The identifier for the customer",
+ "example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
+ "nullable": true,
+ "maxLength": 64,
+ "minLength": 1
+ },
+ "customer_present": {
+ "$ref": "#/components/schemas/PresenceOfCustomerDuringPayment"
+ },
+ "description": {
+ "type": "string",
+ "description": "A description for the payment",
+ "example": "It's my first payment request",
+ "nullable": true
+ },
+ "return_url": {
+ "type": "string",
+ "description": "The URL to which you want the user to be redirected after the completion of the payment operation",
+ "example": "https://hyperswitch.io",
+ "nullable": true
+ },
+ "setup_future_usage": {
+ "$ref": "#/components/schemas/FutureUsage"
+ },
+ "apply_mit_exemption": {
+ "$ref": "#/components/schemas/MitExemptionRequest"
+ },
+ "statement_descriptor": {
+ "type": "string",
+ "description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.",
+ "example": "Hyperswitch Router",
+ "nullable": true,
+ "maxLength": 22
+ },
+ "order_details": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/OrderDetailsWithAmount"
+ },
+ "description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount",
+ "example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]",
+ "nullable": true
+ },
+ "allowed_payment_method_types": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ },
+ "description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent",
+ "nullable": true
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Metadata is useful for storing additional, unstructured information on an object.",
+ "nullable": true
+ },
+ "connector_metadata": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ConnectorMetadata"
+ }
+ ],
+ "nullable": true
+ },
+ "feature_metadata": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/FeatureMetadata"
+ }
+ ],
+ "nullable": true
+ },
+ "payment_link_enabled": {
+ "$ref": "#/components/schemas/EnablePaymentLinkRequest"
+ },
+ "payment_link_config": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ }
+ ],
+ "nullable": true
+ },
+ "request_incremental_authorization": {
+ "$ref": "#/components/schemas/RequestIncrementalAuthorization"
+ },
+ "expires_on": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds"
+ },
+ "frm_metadata": {
+ "type": "object",
+ "description": "Additional data related to some frm(Fraud Risk Management) connectors",
+ "nullable": true
+ },
+ "request_external_three_ds_authentication": {
+ "$ref": "#/components/schemas/External3dsAuthenticationRequest"
+ }
+ },
+ "additionalProperties": false
+ },
"PaymentsResponse": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 000343864b2..b9dc1476fdb 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -2,7 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
#[cfg(feature = "v2")]
use super::{
- PaymentsConfirmIntentResponse, PaymentsCreateIntentRequest, PaymentsCreateIntentResponse,
+ PaymentsConfirmIntentResponse, PaymentsCreateIntentRequest, PaymentsGetIntentRequest,
+ PaymentsIntentResponse,
};
#[cfg(all(
any(feature = "v2", feature = "v1"),
@@ -150,7 +151,16 @@ impl ApiEventMetric for PaymentsCreateIntentRequest {
}
#[cfg(feature = "v2")]
-impl ApiEventMetric for PaymentsCreateIntentResponse {
+impl ApiEventMetric for PaymentsGetIntentRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Payment {
+ payment_id: self.id.clone(),
+ })
+ }
+}
+
+#[cfg(feature = "v2")]
+impl ApiEventMetric for PaymentsIntentResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.id.clone(),
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index fd8419e7f97..564149e4325 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -287,10 +287,17 @@ impl PaymentsCreateIntentRequest {
}
}
+// This struct is only used internally, not visible in API Reference
+#[derive(Debug, Clone, serde::Serialize)]
+#[cfg(feature = "v2")]
+pub struct PaymentsGetIntentRequest {
+ pub id: id_type::GlobalPaymentId,
+}
+
#[derive(Debug, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[cfg(feature = "v2")]
-pub struct PaymentsCreateIntentResponse {
+pub struct PaymentsIntentResponse {
/// Global Payment Id for the payment
#[schema(value_type = String)]
pub id: id_type::GlobalPaymentId,
diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
index 602c184139f..c43d72ce8de 100644
--- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
+++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
@@ -57,7 +57,10 @@ pub struct CalculateTax;
pub struct SdkSessionUpdate;
#[derive(Debug, Clone)]
-pub struct CreateIntent;
+pub struct PaymentCreateIntent;
+
+#[derive(Debug, Clone)]
+pub struct PaymentGetIntent;
#[derive(Debug, Clone)]
pub struct PostSessionTokens;
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index 0a19c5a63c5..c4a734d152f 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -123,6 +123,7 @@ Never share your secret api keys. Keep them guarded and secure.
//Routes for payments
routes::payments::payments_create_intent,
+ routes::payments::payments_get_intent,
routes::payments::payments_confirm_intent,
//Routes for refunds
@@ -325,7 +326,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
- api_models::payments::PaymentsCreateIntentResponse,
+ api_models::payments::PaymentsIntentResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::SessionToken,
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index 3429de60ba7..e245c5af68a 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -620,7 +620,7 @@ pub fn payments_post_session_tokens() {}
),
),
responses(
- (status = 200, description = "Payment created", body = PaymentsCreateIntentResponse),
+ (status = 200, description = "Payment created", body = PaymentsIntentResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payments",
@@ -630,6 +630,25 @@ pub fn payments_post_session_tokens() {}
#[cfg(feature = "v2")]
pub fn payments_create_intent() {}
+/// Payments - Get Intent
+///
+/// **Get a payment intent object when id is passed in path**
+///
+/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
+#[utoipa::path(
+ get,
+ path = "/v2/payments/{id}/get-intent",
+ params (("id" = String, Path, description = "The unique identifier for the Payment Intent")),
+ responses(
+ (status = 200, description = "Payment Intent", body = PaymentsIntentResponse),
+ (status = 404, description = "Payment Intent not found")
+ ),
+ tag = "Payments",
+ operation_id = "Get the Payment Intent details",
+ security(("api_key" = [])),
+)]
+#[cfg(feature = "v2")]
+pub fn payments_get_intent() {}
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 2218197743a..ca142582c14 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1021,7 +1021,7 @@ pub async fn payments_intent_operation_core<F, Req, Op, D>(
) -> RouterResult<(D, Req, Option<domain::Customer>)>
where
F: Send + Clone + Sync,
- Req: Authenticate + Clone,
+ Req: Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
@@ -1454,7 +1454,7 @@ pub async fn payments_intent_core<F, Res, Req, Op, D>(
where
F: Send + Clone + Sync,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
- Req: Debug + Authenticate + Clone,
+ Req: Debug + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
{
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 6546638a62e..b03f41ac0fd 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -28,11 +28,12 @@ pub mod payments_incremental_authorization;
#[cfg(feature = "v1")]
pub mod tax_calculation;
+#[cfg(feature = "v2")]
+pub mod payment_confirm_intent;
#[cfg(feature = "v2")]
pub mod payment_create_intent;
-
#[cfg(feature = "v2")]
-pub mod payment_confirm_intent;
+pub mod payment_get_intent;
use api_models::enums::FrmSuggestion;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
@@ -45,6 +46,8 @@ use router_env::{instrument, tracing};
pub use self::payment_confirm_intent::PaymentIntentConfirm;
#[cfg(feature = "v2")]
pub use self::payment_create_intent::PaymentIntentCreate;
+#[cfg(feature = "v2")]
+pub use self::payment_get_intent::PaymentGetIntent;
pub use self::payment_response::PaymentResponse;
#[cfg(feature = "v1")]
pub use self::{
diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs
new file mode 100644
index 00000000000..55ddc3b482a
--- /dev/null
+++ b/crates/router/src/core/payments/operations/payment_get_intent.rs
@@ -0,0 +1,231 @@
+use std::marker::PhantomData;
+
+use api_models::{enums::FrmSuggestion, payments::PaymentsGetIntentRequest};
+use async_trait::async_trait;
+use common_utils::errors::CustomResult;
+use router_env::{instrument, tracing};
+
+use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
+use crate::{
+ core::{
+ errors::{self, RouterResult},
+ payments::{self, helpers, operations},
+ },
+ db::errors::StorageErrorExt,
+ routes::{app::ReqState, SessionState},
+ types::{
+ api, domain,
+ storage::{self, enums},
+ },
+};
+
+#[derive(Debug, Clone, Copy)]
+pub struct PaymentGetIntent;
+
+impl<F: Send + Clone> Operation<F, PaymentsGetIntentRequest> for &PaymentGetIntent {
+ type Data = payments::PaymentIntentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+ fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsGetIntentRequest, Self::Data>)> {
+ Ok(*self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
+ {
+ Ok(*self)
+ }
+}
+
+impl<F: Send + Clone> Operation<F, PaymentsGetIntentRequest> for PaymentGetIntent {
+ type Data = payments::PaymentIntentData<F>;
+ fn to_validate_request(
+ &self,
+ ) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)>
+ {
+ Ok(self)
+ }
+ fn to_get_tracker(
+ &self,
+ ) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
+ {
+ Ok(self)
+ }
+ fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsGetIntentRequest, Self::Data>> {
+ Ok(self)
+ }
+ fn to_update_tracker(
+ &self,
+ ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
+ {
+ Ok(self)
+ }
+}
+
+type PaymentsGetIntentOperation<'b, F> =
+ BoxedOperation<'b, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>;
+
+#[async_trait]
+impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest>
+ for PaymentGetIntent
+{
+ #[instrument(skip_all)]
+ async fn get_trackers<'a>(
+ &'a self,
+ state: &'a SessionState,
+ _payment_id: &common_utils::id_type::GlobalPaymentId,
+ request: &PaymentsGetIntentRequest,
+ merchant_account: &domain::MerchantAccount,
+ _profile: &domain::Profile,
+ key_store: &domain::MerchantKeyStore,
+ _header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<
+ operations::GetTrackerResponse<
+ 'a,
+ F,
+ PaymentsGetIntentRequest,
+ payments::PaymentIntentData<F>,
+ >,
+ > {
+ let db = &*state.store;
+ let key_manager_state = &state.into();
+ let storage_scheme = merchant_account.storage_scheme;
+ let payment_intent = db
+ .find_payment_intent_by_id(key_manager_state, &request.id, key_store, storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ let payment_data = payments::PaymentIntentData {
+ flow: PhantomData,
+ payment_intent,
+ };
+
+ let get_trackers_response = operations::GetTrackerResponse {
+ operation: Box::new(self),
+ payment_data,
+ };
+
+ Ok(get_trackers_response)
+ }
+}
+
+#[async_trait]
+impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest>
+ for PaymentGetIntent
+{
+ #[instrument(skip_all)]
+ async fn update_trackers<'b>(
+ &'b self,
+ _state: &'b SessionState,
+ _req_state: ReqState,
+ payment_data: payments::PaymentIntentData<F>,
+ _customer: Option<domain::Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
+ _updated_customer: Option<storage::CustomerUpdate>,
+ _key_store: &domain::MerchantKeyStore,
+ _frm_suggestion: Option<FrmSuggestion>,
+ _header_payload: hyperswitch_domain_models::payments::HeaderPayload,
+ ) -> RouterResult<(
+ PaymentsGetIntentOperation<'b, F>,
+ payments::PaymentIntentData<F>,
+ )>
+ where
+ F: 'b + Send,
+ {
+ Ok((Box::new(self), payment_data))
+ }
+}
+
+impl<F: Send + Clone> ValidateRequest<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>
+ for PaymentGetIntent
+{
+ #[instrument(skip_all)]
+ fn validate_request<'a, 'b>(
+ &'b self,
+ _request: &PaymentsGetIntentRequest,
+ merchant_account: &'a domain::MerchantAccount,
+ ) -> RouterResult<(
+ PaymentsGetIntentOperation<'b, F>,
+ operations::ValidateResult,
+ )> {
+ Ok((
+ Box::new(self),
+ operations::ValidateResult {
+ merchant_id: merchant_account.get_id().to_owned(),
+ storage_scheme: merchant_account.storage_scheme,
+ requeue: false,
+ },
+ ))
+ }
+}
+
+#[async_trait]
+impl<F: Clone + Send> Domain<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>
+ for PaymentGetIntent
+{
+ #[instrument(skip_all)]
+ async fn get_customer_details<'a>(
+ &'a self,
+ state: &SessionState,
+ payment_data: &mut payments::PaymentIntentData<F>,
+ merchant_key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<
+ (
+ BoxedOperation<'a, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>,
+ Option<domain::Customer>,
+ ),
+ errors::StorageError,
+ > {
+ Ok((Box::new(self), None))
+ }
+
+ #[instrument(skip_all)]
+ async fn make_pm_data<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ _storage_scheme: enums::MerchantStorageScheme,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _customer: &Option<domain::Customer>,
+ _business_profile: &domain::Profile,
+ ) -> RouterResult<(
+ PaymentsGetIntentOperation<'a, F>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+ )> {
+ Ok((Box::new(self), None, None))
+ }
+
+ async fn get_connector<'a>(
+ &'a self,
+ _merchant_account: &domain::MerchantAccount,
+ state: &SessionState,
+ _request: &PaymentsGetIntentRequest,
+ _payment_intent: &storage::PaymentIntent,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
+ helpers::get_connector_default(state, None).await
+ }
+
+ #[instrument(skip_all)]
+ async fn guard_payment_against_blocklist<'a>(
+ &'a self,
+ _state: &SessionState,
+ _merchant_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ _payment_data: &mut payments::PaymentIntentData<F>,
+ ) -> CustomResult<bool, errors::ApiErrorResponse> {
+ Ok(false)
+ }
+}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 58ea3b43462..9f5aa7b0c59 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -754,7 +754,7 @@ where
}
#[cfg(feature = "v2")]
-impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsCreateIntentResponse
+impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsIntentResponse
where
F: Clone,
Op: Debug,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 33699ed266a..ec68af2ed90 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -527,6 +527,10 @@ impl Payments {
web::resource("/confirm-intent")
.route(web::post().to(payments::payment_confirm_intent)),
)
+ .service(
+ web::resource("/get-intent")
+ .route(web::get().to(payments::payments_get_intent)),
+ )
.service(
web::resource("/create-external-sdk-tokens")
.route(web::post().to(payments::payments_connector_session)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index a0c5c0f9902..eaaa7795c8c 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -139,6 +139,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::SessionUpdateTaxCalculation
| Flow::PaymentsConfirmIntent
| Flow::PaymentsCreateIntent
+ | Flow::PaymentsGetIntent
| Flow::PaymentsPostSessionTokens => Self::Payments,
Flow::PayoutsCreate
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index f13a873473a..ac00e009f17 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -127,11 +127,11 @@ pub async fn payments_create_intent(
json_payload.into_inner(),
|state, auth: auth::AuthenticationDataV2, req, req_state| {
payments::payments_intent_core::<
- api_types::CreateIntent,
- payment_types::PaymentsCreateIntentResponse,
+ api_types::PaymentCreateIntent,
+ payment_types::PaymentsIntentResponse,
_,
_,
- PaymentIntentData<api_types::CreateIntent>,
+ PaymentIntentData<api_types::PaymentCreateIntent>,
>(
state,
req_state,
@@ -159,6 +159,57 @@ pub async fn payments_create_intent(
.await
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentsGetIntent, payment_id))]
+pub async fn payments_get_intent(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ path: web::Path<common_utils::id_type::GlobalPaymentId>,
+) -> impl Responder {
+ use api_models::payments::PaymentsGetIntentRequest;
+ use hyperswitch_domain_models::payments::PaymentIntentData;
+
+ let flow = Flow::PaymentsGetIntent;
+ let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
+ Ok(headers) => headers,
+ Err(err) => {
+ return api::log_and_return_error_response(err);
+ }
+ };
+
+ let payload = PaymentsGetIntentRequest {
+ id: path.into_inner(),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationDataV2, req, req_state| {
+ payments::payments_intent_core::<
+ api_types::PaymentGetIntent,
+ payment_types::PaymentsIntentResponse,
+ _,
+ _,
+ PaymentIntentData<api_types::PaymentGetIntent>,
+ >(
+ state,
+ req_state,
+ auth.merchant_account,
+ auth.profile,
+ auth.key_store,
+ payments::operations::PaymentGetIntent,
+ req,
+ header_payload.clone(),
+ )
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v1")]
#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart, payment_id))]
pub async fn payments_start(
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 6f6eb381669..d9da8a7226f 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1263,10 +1263,8 @@ impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequ
impl Authenticate for api_models::payments::PaymentsStartRequest {}
// impl Authenticate for api_models::payments::PaymentsApproveRequest {}
impl Authenticate for api_models::payments::PaymentsRejectRequest {}
-#[cfg(feature = "v2")]
-impl Authenticate for api_models::payments::PaymentsCreateIntentRequest {}
// #[cfg(feature = "v2")]
-// impl Authenticate for api_models::payments::PaymentsCreateIntentResponse {}
+// impl Authenticate for api_models::payments::PaymentsIntentResponse {}
pub fn build_redirection_form(
form: &RedirectForm,
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index fc13cc6a22b..57ef1d3336f 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -19,13 +19,13 @@ pub use api_models::payments::{
VerifyResponse, WalletData,
};
#[cfg(feature = "v2")]
-pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsCreateIntentResponse};
+pub use api_models::payments::{PaymentsCreateIntentRequest, PaymentsIntentResponse};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
- CreateConnectorCustomer, CreateIntent, IncrementalAuthorization, InitPayment, PSync,
- PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate,
- Session, SetupMandate, Void,
+ CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentCreateIntent,
+ PaymentGetIntent, PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Reject,
+ SdkSessionUpdate, Session, SetupMandate, Void,
};
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 8d853ded338..3bd8a13628e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -171,6 +171,8 @@ pub enum Flow {
PaymentsAggregate,
/// Payments Create Intent flow
PaymentsCreateIntent,
+ /// Payments Get Intent flow
+ PaymentsGetIntent,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
|
2024-10-22T12:37:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Added `get-intent` API for payments
### 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 #6395
## How did you test 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. Request
```
curl --location 'http://localhost:8080/v2/payments/12345_pay_0192b3a0145173519abaa04d4b939558/get-intent' \
--header 'Content-Type: application/json' \
--header 'X-Profile-Id: pro_wcilqiS8axGFvpzfO9pw' \
--header 'api-key: dev_D3bTAROAIoP4nlqsaQXLzXoLdZznkpWQ3l4mzMRJEAP7V46pSnZucJM2zQiVwG0J'
```
1b. Response
```json
{
"id": "12345_pay_0192b3a0145173519abaa04d4b939558",
"amount_details": {
"order_amount": {
"Value": 100
},
"currency": "USD",
"shipping_cost": null,
"order_tax_amount": null,
"skip_external_tax_calculation": "Skip",
"skip_surcharge_calculation": "Skip",
"surcharge_amount": null,
"tax_on_surcharge": null
},
"client_secret": "12345_pay_0192b3a0145173519abaa04d4b939558_secret_0192b3a0145173519abaa05c07ec3e61",
"merchant_reference_id": null,
"routing_algorithm_id": null,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"billing": null,
"shipping": null,
"customer_id": null,
"customer_present": "Present",
"description": null,
"return_url": null,
"setup_future_usage": "on_session",
"apply_mit_exemption": "Skip",
"statement_descriptor": null,
"order_details": null,
"allowed_payment_method_types": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"payment_link_enabled": "Skip",
"payment_link_config": null,
"request_incremental_authorization": "default",
"expires_on": "2024-10-22T10:02:45.618Z",
"frm_metadata": null,
"request_external_three_ds_authentication": "Skip"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
fbe395198aea7252e9c4e3fad97956a548d07002
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6387
|
Bug: include the payment_processing_details_at Hyperswitch option only if apple pay token decryption flow is supported for the connector
While configuring apple pay iOS flow `payment_processing_details_at` option is shown that can take two values ,`Connector` or `Hyperswitch`. But the `payment_processing_details_at` can be `Hyperswitch` only if the apple pay token decryption flow is implemented for the connector.
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 78f3c627fca..180aadffde3 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -281,7 +281,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[adyen.metadata.google_pay]]
name="merchant_name"
@@ -484,7 +484,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[authorizedotnet.metadata.google_pay]]
name="merchant_name"
@@ -813,7 +813,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[bluesnap.metadata.google_pay]]
name="merchant_name"
@@ -1115,7 +1115,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[checkout.metadata.google_pay]]
name="merchant_name"
@@ -1941,7 +1941,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[nexixpay]
[[nexixpay.credit]]
@@ -2062,7 +2062,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[nmi.metadata.google_pay]]
name="merchant_name"
@@ -2202,7 +2202,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[noon.metadata.google_pay]]
name="merchant_name"
@@ -2379,7 +2379,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[nuvei.metadata.google_pay]]
name="merchant_name"
@@ -2839,7 +2839,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[shift4]
[[shift4.credit]]
@@ -3244,7 +3244,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[trustpay.metadata.google_pay]]
name="merchant_name"
@@ -3473,7 +3473,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[worldpay.metadata.google_pay]]
name="merchant_name"
@@ -4196,7 +4196,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
\ No newline at end of file
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 9ca992ecad4..c7849fcc227 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -188,7 +188,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[adyen.metadata.google_pay]]
name="merchant_name"
@@ -352,7 +352,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[authorizedotnet.metadata.google_pay]]
name="merchant_name"
@@ -477,7 +477,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[bluesnap.metadata.google_pay]]
name="merchant_name"
@@ -970,7 +970,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[checkout.metadata.google_pay]]
name="merchant_name"
@@ -1680,7 +1680,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[nexixpay]
[[nexixpay.credit]]
@@ -2054,7 +2054,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[shift4]
[[shift4.credit]]
@@ -2359,7 +2359,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[trustpay.metadata.google_pay]]
name="merchant_name"
@@ -2529,7 +2529,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[worldpay.metadata.google_pay]]
name="merchant_name"
@@ -3191,7 +3191,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
\ No newline at end of file
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 39421babc87..2a753008e81 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -280,7 +280,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[adyen.metadata.google_pay]]
name="merchant_name"
@@ -488,7 +488,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[authorizedotnet.metadata.google_pay]]
name="merchant_name"
@@ -814,7 +814,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[bluesnap.metadata.google_pay]]
name="merchant_name"
@@ -1115,7 +1115,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[checkout.metadata.google_pay]]
name="merchant_name"
@@ -1939,7 +1939,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[nexixpay]
[[nexixpay.credit]]
@@ -2059,7 +2059,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[nmi.metadata.google_pay]]
name="merchant_name"
@@ -2198,7 +2198,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[noon.metadata.google_pay]]
name="merchant_name"
@@ -2374,7 +2374,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[nuvei.metadata.google_pay]]
name="merchant_name"
@@ -2832,7 +2832,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[shift4]
[[shift4.credit]]
@@ -3235,7 +3235,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[trustpay.metadata.google_pay]]
name="merchant_name"
@@ -3462,7 +3462,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Connector"]
[[worldpay.metadata.google_pay]]
name="merchant_name"
@@ -4190,7 +4190,7 @@ label="Payment Processing Details At"
placeholder="Enter Payment Processing Details At"
required=true
type="Radio"
-options=["Connector","Hyperswitch"]
+options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
\ No newline at end of file
|
2024-10-22T06:55:26Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
While configuring apple pay iOS flow `payment_processing_details_at` option is shown that can take two values ,`Connector` or `Hyperswitch`. But the `payment_processing_details_at` can be `Hyperswitch` only if the apple pay token decryption flow is implemented for the connector.
Currently both connector tokenization and decrypted flow is supported only by Stripe, BOA and Cybersource.
And Fiu supports only the decrypted 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)?
-->
This pr includes wasam changes to not show the `payment_processing_details_at` `Hyperswitch` when the web apple pay flow is not enabled.
Things to test the below radio button with Hyperswitch option should not be shown if apple pay web flow is not enalbed.
<img width="562" alt="image" src="https://github.com/user-attachments/assets/1153ebaf-59ca-4098-beeb-afff707fa405">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f3a869ea9a430f3b5177852fb74d0910dc8fbe17
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6390
|
Bug: [FIX] fix tenant nomenclature in the code
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 8f04ba49831..b0d3c743673 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -741,7 +741,7 @@ enabled = false
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" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant
+public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant
[user_auth_methods]
encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index cfefe9a130f..0eab330652a 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -305,7 +305,7 @@ enabled = false
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" }
+public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
[user_auth_methods]
encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table
diff --git a/config/development.toml b/config/development.toml
index d32c3610132..274e605193f 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -750,7 +750,7 @@ enabled = false
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"}
+public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
[user_auth_methods]
encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index dde0902af91..c8436efd022 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -575,7 +575,7 @@ enabled = false
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" }
+public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" }
[user_auth_methods]
encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F"
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index 05226739504..5b391b492e0 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -125,21 +125,56 @@ impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<String, Tenant> {
&self.tenants.0
}
- pub fn get_tenant_names(&self) -> Vec<String> {
- self.tenants.0.keys().cloned().collect()
+ pub fn get_tenant_ids(&self) -> Vec<String> {
+ self.tenants
+ .0
+ .values()
+ .map(|tenant| tenant.tenant_id.clone())
+ .collect()
}
pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
}
}
-#[derive(Debug, Deserialize, Clone, Default)]
-#[serde(transparent)]
+#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<String, Tenant>);
+impl<'de> Deserialize<'de> for TenantConfig {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ #[derive(Deserialize)]
+ struct Inner {
+ base_url: String,
+ schema: String,
+ redis_key_prefix: String,
+ clickhouse_database: String,
+ }
+
+ let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?;
+
+ Ok(Self(
+ hashmap
+ .into_iter()
+ .map(|(key, value)| {
+ (
+ key.clone(),
+ Tenant {
+ tenant_id: key,
+ base_url: value.base_url,
+ schema: value.schema,
+ redis_key_prefix: value.redis_key_prefix,
+ clickhouse_database: value.clickhouse_database,
+ },
+ )
+ })
+ .collect(),
+ ))
+ }
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Tenant {
- pub name: String,
+ pub tenant_id: String,
pub base_url: String,
pub schema: String,
pub redis_key_prefix: String,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 149ee2b8456..61e026ae2c5 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -141,8 +141,12 @@ impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<String, Tenant> {
&self.tenants.0
}
- pub fn get_tenant_names(&self) -> Vec<String> {
- self.tenants.0.keys().cloned().collect()
+ pub fn get_tenant_ids(&self) -> Vec<String> {
+ self.tenants
+ .0
+ .values()
+ .map(|tenant| tenant.tenant_id.clone())
+ .collect()
}
pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
@@ -154,13 +158,12 @@ pub struct DecisionConfig {
pub base_url: String,
}
-#[derive(Debug, Deserialize, Clone, Default)]
-#[serde(transparent)]
+#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<String, Tenant>);
-#[derive(Debug, Deserialize, Clone, Default)]
+#[derive(Debug, Clone, Default)]
pub struct Tenant {
- pub name: String,
+ pub tenant_id: String,
pub base_url: String,
pub schema: String,
pub redis_key_prefix: String,
@@ -1102,6 +1105,38 @@ where
})?
}
+impl<'de> Deserialize<'de> for TenantConfig {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ #[derive(Deserialize)]
+ struct Inner {
+ base_url: String,
+ schema: String,
+ redis_key_prefix: String,
+ clickhouse_database: String,
+ }
+
+ let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?;
+
+ Ok(Self(
+ hashmap
+ .into_iter()
+ .map(|(key, value)| {
+ (
+ key.clone(),
+ Tenant {
+ tenant_id: key,
+ base_url: value.base_url,
+ schema: value.schema,
+ redis_key_prefix: value.redis_key_prefix,
+ clickhouse_database: value.clickhouse_database,
+ },
+ )
+ })
+ .collect(),
+ ))
+ }
+}
+
#[cfg(test)]
mod hashmap_deserialization_test {
#![allow(clippy::unwrap_used)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 067b35e1e5e..990a0f0e9ad 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2058,7 +2058,7 @@ pub async fn get_payment_method_from_hs_locker<'a>(
merchant_id,
payment_method_reference,
locker_choice,
- state.tenant.name.clone(),
+ state.tenant.tenant_id.clone(),
state.request_id,
)
.await
@@ -2112,7 +2112,7 @@ pub async fn add_card_to_hs_locker(
locker,
payload,
locker_choice,
- state.tenant.name.clone(),
+ state.tenant.tenant_id.clone(),
state.request_id,
)
.await?;
@@ -2309,7 +2309,7 @@ pub async fn get_card_from_hs_locker<'a>(
merchant_id,
card_reference,
Some(locker_choice),
- state.tenant.name.clone(),
+ state.tenant.tenant_id.clone(),
state.request_id,
)
.await
@@ -2355,7 +2355,7 @@ pub async fn delete_card_from_hs_locker<'a>(
customer_id,
merchant_id,
card_reference,
- state.tenant.name.clone(),
+ state.tenant.tenant_id.clone(),
state.request_id,
)
.await
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 6b584583174..31cd4234714 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -739,7 +739,7 @@ pub async fn push_metrics_for_success_based_routing(
&metrics::CONTEXT,
1,
&add_attributes([
- ("tenant", state.tenant.name.clone()),
+ ("tenant", state.tenant.tenant_id.clone()),
(
"merchant_id",
payment_attempt.merchant_id.get_string_repr().to_string(),
diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs
index c80d14b9e25..0185d8a0768 100644
--- a/crates/router/src/middleware.rs
+++ b/crates/router/src/middleware.rs
@@ -147,10 +147,11 @@ where
.and_then(|i| i.to_str().ok())
.map(|s| s.to_owned());
let response_fut = self.service.call(req);
+ let tenant_id_clone = tenant_id.clone();
Box::pin(
async move {
- if let Some(tenant_id) = tenant_id {
- router_env::tracing::Span::current().record("tenant_id", &tenant_id);
+ if let Some(tenant) = tenant_id_clone {
+ router_env::tracing::Span::current().record("tenant_id", tenant);
}
let response = response_fut.await;
router_env::tracing::Span::current().record("golden_log_line", true);
@@ -166,7 +167,7 @@ where
status_code = Empty,
flow = "UNKNOWN",
golden_log_line = Empty,
- tenant_id = "ta"
+ tenant_id = &tenant_id
)
.or_current(),
),
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 33699ed266a..f11840edf63 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -207,7 +207,7 @@ pub struct AppState {
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<String> {
- self.conf.multitenancy.get_tenant_names()
+ self.conf.multitenancy.get_tenant_ids()
}
}
pub trait AppStateInfo {
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 6f6eb381669..02d4950a47d 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -721,31 +721,27 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut event_type = payload.get_api_event_type();
- let tenants: HashSet<_> = state
- .conf
- .multitenancy
- .get_tenant_names()
- .into_iter()
- .collect();
let tenant_id = if !state.conf.multitenancy.enabled {
DEFAULT_TENANT.to_string()
} else {
- incoming_request_header
+ let request_tenant_id = incoming_request_header
.get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
- .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
- .map(|req_tenant_id| {
- if !tenants.contains(req_tenant_id) {
- Err(errors::ApiErrorResponse::InvalidTenant {
- tenant_id: req_tenant_id.to_string(),
- }
- .switch())
- } else {
- Ok(req_tenant_id.to_string())
+ .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())?;
+
+ state
+ .conf
+ .multitenancy
+ .get_tenant(request_tenant_id)
+ .map(|tenant| tenant.tenant_id.clone())
+ .ok_or(
+ errors::ApiErrorResponse::InvalidTenant {
+ tenant_id: request_tenant_id.to_string(),
}
- })??
+ .switch(),
+ )?
};
- // let tenant_id = "public".to_string();
+
let mut session_state =
Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || {
errors::ApiErrorResponse::InvalidTenant {
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 98f51725bbe..0291374d54f 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -221,7 +221,7 @@ mod tests {
let store = state
.stores
- .get(state.conf.multitenancy.get_tenant_names().first().unwrap())
+ .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let response = store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
@@ -304,7 +304,7 @@ mod tests {
};
let store = state
.stores
- .get(state.conf.multitenancy.get_tenant_names().first().unwrap())
+ .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
@@ -401,7 +401,7 @@ mod tests {
};
let store = state
.stores
- .get(state.conf.multitenancy.get_tenant_names().first().unwrap())
+ .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index c8a5ccf9228..11268e15e54 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -369,7 +369,7 @@ enabled = false
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"}
+public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}
[email]
sender_email = "example@example.com"
|
2024-10-22T09:27:55Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
This fixes the inconsistent nomenclature used for tenants in router and drainer code
### Additional Changes
- [x] This PR modifies application configuration/environment variables
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This will eradicate confusion between `name` and `tenant_id` names in the tenant config. In the config below
`public = { base_url = "http://localhost:8080/", schema = "public", redis_key_prefix = "", clickhouse_database = "default"}`
The key `public` will be the tenant_id. This PR adds a custom deserializer for this part
## How did you test 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 sandbox without enabling Multi Tenancy**
1. Application runs with the changed config and so does drainer
2. Do a request with a valid `x-tenant-id`
```bash
curl --location 'http://localhost:8080/accounts' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-tenant-id: public' \
--header 'api-key: test_admin' \
--data-raw '{
"merchant_id": "1729601216",
"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://google.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
"payment_created_enabled": true,
"payment_succeeded_enabled": true,
"payment_failed_enabled": true
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
},
"primary_business_details": [
{
"country": "US",
"business": "default"
}
]
}'
```
It should return 200 and `tenant-id` should be the which has been passed
3. Try the request with invalid `tenant-id`, It should return an error
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
04c969866816be286720377e73982e21a3302ba9
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6391
|
Bug: feat(authz): Make permissions entity and scope aware
Currently the permissions we use doesn't have any entity level context. But some of our APIs need that context.
For example,
1. `payment/list` - This can only be accessible by merchant level users or higher. Profile level users should not be able to access it.
2. `payment/profile/list` - This can be accessible by all level of users.
With current setup, this is not directly possible by the permissions. We had to introduce `min_entity_level` to solve this, but this is very separated from the permissions.
To solve this, we need to have entity level context at permissions level itself.
### Scope for permissions
The write permissions currently doesn't have access to read APIs, but since write is a superset of read, they should be able to access read APIs as well.
So, this PR also introduces scope context in permissions.
|
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index e64639646d1..19027c3cbf8 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,23 +1,9 @@
-use common_enums::PermissionGroup;
+use common_enums::{ParentGroup, PermissionGroup};
use common_utils::pii;
use masking::Secret;
pub mod role;
-#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
-pub enum ParentGroup {
- Operations,
- Connectors,
- Workflows,
- Analytics,
- Users,
- #[serde(rename = "MerchantAccess")]
- Merchant,
- #[serde(rename = "OrganizationAccess")]
- Organization,
- Recon,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3ce9d079c63..c103153eec8 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2890,6 +2890,47 @@ pub enum PermissionGroup {
ReconOps,
}
+#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)]
+pub enum ParentGroup {
+ Operations,
+ Connectors,
+ Workflows,
+ Analytics,
+ Users,
+ #[serde(rename = "MerchantAccess")]
+ Merchant,
+ #[serde(rename = "OrganizationAccess")]
+ Organization,
+ Recon,
+}
+
+#[derive(Clone, Copy, Eq, PartialEq, Hash)]
+pub enum Resource {
+ Payment,
+ Refund,
+ ApiKey,
+ Account,
+ Connector,
+ Routing,
+ Dispute,
+ Mandate,
+ Customer,
+ Analytics,
+ ThreeDsDecisionManager,
+ SurchargeDecisionManager,
+ User,
+ WebhookEvent,
+ Payout,
+ Report,
+ Recon,
+}
+
+#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
+pub enum PermissionScope {
+ Read,
+ Write,
+}
+
/// Name of banks supported by Hyperswitch
#[derive(
Clone,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index aa6db56bb34..150931e9c8a 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -402,8 +402,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -441,8 +440,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -487,8 +485,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -528,8 +525,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -567,8 +563,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -613,8 +608,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -654,8 +648,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -693,8 +686,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -739,8 +731,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -774,8 +765,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -813,8 +803,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -853,8 +842,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -893,8 +881,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -924,8 +911,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -953,8 +939,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -989,8 +974,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1018,8 +1002,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1049,8 +1032,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1078,8 +1060,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1114,8 +1095,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1139,8 +1119,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1168,8 +1147,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1201,8 +1179,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1235,8 +1212,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1267,8 +1243,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1318,8 +1293,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1367,8 +1341,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1423,8 +1396,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1474,8 +1446,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1523,8 +1494,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1579,8 +1549,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1630,8 +1599,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1679,8 +1647,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1734,8 +1701,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::GenerateReport,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileReportRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1773,8 +1739,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1798,8 +1763,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1830,8 +1794,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1948,8 +1911,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2065,8 +2027,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2096,8 +2057,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2132,8 +2092,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2161,8 +2120,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2202,8 +2160,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2248,8 +2205,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2287,8 +2243,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2319,8 +2274,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2349,8 +2303,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Organization,
+ permission: Permission::OrganizationAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -2386,8 +2339,7 @@ pub mod routes {
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
- permission: Permission::Analytics,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 1d188168e5c..284be4ab4ba 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -16,14 +16,14 @@ use crate::{
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
- authorization::{info, roles},
+ authorization::{info, permission_groups::PermissionGroupExt, roles},
ApplicationResponse,
},
types::domain,
utils,
};
pub mod role;
-use common_enums::{EntityType, PermissionGroup};
+use common_enums::{EntityType, ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
@@ -44,11 +44,10 @@ 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(|| {
PermissionGroup::iter()
- .map(|value| (info::get_parent_name(value), value))
+ .map(|group| (group.parent(), group))
.fold(
HashMap::new(),
- |mut acc: HashMap<user_role_api::ParentGroup, Vec<PermissionGroup>>,
- (key, value)| {
+ |mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| {
acc.entry(key).or_default().push(value);
acc
},
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 78238d3af07..b197101d65f 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -52,8 +51,7 @@ pub async fn organization_update(
&auth::AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
- required_permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Organization,
+ required_permission: Permission::OrganizationAccountWrite,
},
req.headers(),
),
@@ -85,8 +83,7 @@ pub async fn organization_retrieve(
&auth::AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
- required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Organization,
+ required_permission: Permission::OrganizationAccountRead,
},
req.headers(),
),
@@ -139,8 +136,11 @@ pub async fn retrieve_merchant_account(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ // This should ideally be MerchantAccountRead, but since FE is calling this API for
+ // profile level users currently keeping this as ProfileAccountRead. FE is removing
+ // this API call for profile level users.
+ // TODO: Convert this to MerchantAccountRead once FE changes are done.
+ required_permission: Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -172,7 +172,6 @@ pub async fn merchant_account_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -200,7 +199,6 @@ pub async fn merchant_account_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -232,7 +230,6 @@ pub async fn update_merchant_account(
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -298,8 +295,7 @@ pub async fn connector_create(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
@@ -336,8 +332,7 @@ pub async fn connector_create(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -399,8 +394,7 @@ pub async fn connector_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
@@ -438,8 +432,7 @@ pub async fn connector_retrieve(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -469,8 +462,7 @@ pub async fn connector_list(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -517,8 +509,7 @@ pub async fn connector_list(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
@@ -569,8 +560,7 @@ pub async fn connector_list_profile(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
@@ -631,8 +621,7 @@ pub async fn connector_update(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
@@ -683,8 +672,7 @@ pub async fn connector_update(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -739,8 +727,7 @@ pub async fn connector_delete(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
@@ -778,8 +765,7 @@ pub async fn connector_delete(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index bbecaae9e80..1a2f60bcccb 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, Responder};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -33,8 +32,7 @@ pub async fn api_key_create(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -64,8 +62,7 @@ pub async fn api_key_create(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -99,8 +96,7 @@ pub async fn api_key_retrieve(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -132,8 +128,7 @@ pub async fn api_key_retrieve(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -169,8 +164,7 @@ pub async fn api_key_update(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -203,8 +197,7 @@ pub async fn api_key_update(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -236,8 +229,7 @@ pub async fn api_key_revoke(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -269,8 +261,7 @@ pub async fn api_key_revoke(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: Permission::ApiKeyWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyWrite,
},
req.headers(),
),
@@ -305,8 +296,7 @@ pub async fn api_key_list(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
@@ -336,8 +326,7 @@ pub async fn api_key_list(
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
- required_permission: Permission::ApiKeyRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantApiKeyRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index 4738df5ed2c..f54f61d8a00 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
-use common_enums::EntityType;
use router_env::Flow;
use crate::{
@@ -39,7 +38,6 @@ pub async fn add_entry_to_blocklist(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -78,7 +76,6 @@ pub async fn remove_entry_from_blocklist(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -119,7 +116,6 @@ pub async fn list_blocked_payment_methods(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -160,7 +156,6 @@ pub async fn toggle_blocklist_guard(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs
index f7494e182c1..8ecd321df94 100644
--- a/crates/router/src/routes/connector_onboarding.rs
+++ b/crates/router/src/routes/connector_onboarding.rs
@@ -1,6 +1,5 @@
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;
@@ -24,7 +23,6 @@ pub async fn get_action_url(
core::get_action_url,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -46,7 +44,6 @@ pub async fn sync_onboarding_status(
core::sync_onboarding_status,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -68,7 +65,6 @@ pub async fn reset_tracking_id(
core::reset_tracking_id,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 536bca10f3d..5ff155966a0 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -1,5 +1,4 @@
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};
@@ -29,8 +28,7 @@ pub async fn customers_create(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -55,8 +53,7 @@ pub async fn customers_retrieve(
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
})
} else {
match auth::is_ephemeral_auth(req.headers()) {
@@ -98,8 +95,7 @@ pub async fn customers_retrieve(
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
})
} else {
match auth::is_ephemeral_auth(req.headers()) {
@@ -148,8 +144,7 @@ pub async fn customers_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerRead,
},
req.headers(),
),
@@ -187,8 +182,7 @@ pub async fn customers_update(
auth::auth_type(
&auth::ApiKeyAuth,
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -225,8 +219,7 @@ pub async fn customers_update(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -256,8 +249,7 @@ pub async fn customers_delete(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -290,8 +282,7 @@ pub async fn customers_delete(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::CustomerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantCustomerWrite,
},
req.headers(),
),
@@ -328,8 +319,7 @@ pub async fn get_customer_mandates(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MandateRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantMandateRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 22c1e3f1988..5577bb96ef0 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -1,7 +1,6 @@
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};
@@ -50,8 +49,7 @@ pub async fn retrieve_dispute(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -102,8 +100,7 @@ pub async fn retrieve_disputes_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -160,8 +157,7 @@ pub async fn retrieve_disputes_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -195,8 +191,7 @@ pub async fn get_disputes_filters(state: web::Data<AppState>, req: HttpRequest)
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -237,8 +232,7 @@ pub async fn get_disputes_filters_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -289,8 +283,7 @@ pub async fn accept_dispute(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -335,8 +328,7 @@ pub async fn submit_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -389,8 +381,7 @@ pub async fn attach_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -435,8 +426,7 @@ pub async fn retrieve_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
@@ -478,8 +468,7 @@ pub async fn delete_dispute_evidence(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeWrite,
},
req.headers(),
),
@@ -508,8 +497,7 @@ pub async fn get_disputes_aggregate(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantDisputeRead,
},
req.headers(),
),
@@ -543,8 +531,7 @@ pub async fn get_disputes_aggregate_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::DisputeRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileDisputeRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs
index c0ccbfa9f8f..cb832d81a16 100644
--- a/crates/router/src/routes/mandates.rs
+++ b/crates/router/src/routes/mandates.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -117,8 +116,7 @@ pub async fn retrieve_mandates_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MandateRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantMandateRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 8d95ee64ad0..0dbddbef77b 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -4,7 +4,6 @@
))]
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;
@@ -881,15 +880,13 @@ pub async fn list_countries_currencies_for_connector_payment_method(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileConnectorWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index f13a873473a..bca7bd37ccc 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -5,7 +5,6 @@ use crate::{
pub mod helpers;
use actix_web::{web, Responder};
-use common_enums::EntityType;
use error_stack::report;
use hyperswitch_domain_models::payments::HeaderPayload;
use masking::PeekInterface;
@@ -93,8 +92,7 @@ pub async fn payments_create(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
@@ -148,8 +146,7 @@ pub async fn payments_create_intent(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
req.headers(),
),
@@ -285,8 +282,7 @@ pub async fn payments_retrieve(
auth::auth_type(
&*auth_type,
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
@@ -995,8 +991,7 @@ pub async fn payments_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
req.headers(),
),
@@ -1031,8 +1026,7 @@ pub async fn profile_payments_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
req.headers(),
),
@@ -1065,8 +1059,7 @@ pub async fn payments_list_by_filter(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1097,8 +1090,7 @@ pub async fn profile_payments_list_by_filter(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1123,8 +1115,7 @@ pub async fn get_filters_for_payments(
payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1147,8 +1138,7 @@ pub async fn get_payment_filters(
payments::get_payment_filters(state, auth.merchant_account, None)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1175,8 +1165,7 @@ pub async fn get_payment_filters_profile(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1201,8 +1190,7 @@ pub async fn get_payments_aggregates(
payments::get_aggregates_for_payments(state, auth.merchant_account, None, req)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -1262,8 +1250,7 @@ pub async fn payments_approve(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
@@ -1327,8 +1314,7 @@ pub async fn payments_reject(
_ => auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentWrite,
},
http_req.headers(),
),
@@ -1970,8 +1956,7 @@ pub async fn get_payments_aggregates_profile(
)
},
&auth::JWTAuth {
- permission: Permission::PaymentRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePaymentRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index ad860195a2a..62d16c4c4d5 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -3,7 +3,6 @@ use actix_web::{
http::header::HeaderMap,
web, HttpRequest, HttpResponse, Responder,
};
-use common_enums::EntityType;
use common_utils::consts;
use router_env::{instrument, tracing, Flow};
@@ -84,8 +83,7 @@ pub async fn payouts_retrieve(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -237,8 +235,7 @@ pub async fn payouts_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -277,8 +274,7 @@ pub async fn payouts_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -317,8 +313,7 @@ pub async fn payouts_list_by_filter(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -357,8 +352,7 @@ pub async fn payouts_list_by_filter_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
@@ -390,8 +384,7 @@ pub async fn payouts_list_available_filters_for_merchant(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPayoutRead,
},
req.headers(),
),
@@ -429,8 +422,7 @@ pub async fn payouts_list_available_filters_for_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::PayoutRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfilePayoutRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/profiles.rs b/crates/router/src/routes/profiles.rs
index f2dc322af17..cbb7957987f 100644
--- a/crates/router/src/routes/profiles.rs
+++ b/crates/router/src/routes/profiles.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -34,7 +33,6 @@ pub async fn profile_create(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -65,7 +63,6 @@ pub async fn profile_create(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -97,8 +94,7 @@ pub async fn profile_retrieve(
&auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()),
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
- required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -127,7 +123,6 @@ pub async fn profile_retrieve(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -161,8 +156,7 @@ pub async fn profile_update(
&auth::JWTAuthMerchantAndProfileFromRoute {
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
- required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountWrite,
},
req.headers(),
),
@@ -192,7 +186,6 @@ pub async fn profile_update(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: permissions::Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -244,7 +237,6 @@ pub async fn profiles_list(
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
@@ -278,8 +270,7 @@ pub async fn profiles_list_at_profile_level(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: permissions::Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileAccountRead,
},
req.headers(),
),
@@ -312,8 +303,7 @@ pub async fn toggle_connector_agnostic_mit(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: permissions::Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: permissions::Permission::MerchantRoutingWrite,
},
req.headers(),
),
@@ -372,8 +362,7 @@ pub async fn payment_connector_list_profile(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: permissions::Permission::MerchantConnectorAccountRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: permissions::Permission::ProfileConnectorRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs
index 1ec571ff7c9..cdc2ae758e9 100644
--- a/crates/router/src/routes/recon.rs
+++ b/crates/router/src/routes/recon.rs
@@ -1,5 +1,5 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::{enums::EntityType, recon as recon_api};
+use api_models::recon as recon_api;
use router_env::Flow;
use super::AppState;
@@ -38,8 +38,7 @@ pub async fn request_for_recon(state: web::Data<AppState>, http_req: HttpRequest
(),
|state, user, _, _| recon::send_recon_request(state, user),
&authentication::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -55,8 +54,7 @@ pub async fn get_recon_token(state: web::Data<AppState>, req: HttpRequest) -> Ht
(),
|state, user, _, _| recon::generate_recon_token(state, user),
&authentication::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index c76ee600efe..cbcfbcdcbf1 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -49,8 +48,7 @@ pub async fn refunds_create(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundWrite,
},
req.headers(),
),
@@ -113,8 +111,7 @@ pub async fn refunds_retrieve(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -245,8 +242,7 @@ pub async fn refunds_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -293,8 +289,7 @@ pub async fn refunds_list_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -336,8 +331,7 @@ pub async fn refunds_filter_list(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -374,8 +368,7 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) -
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -419,8 +412,7 @@ pub async fn get_refunds_filters_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
@@ -449,8 +441,7 @@ pub async fn get_refunds_aggregates(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRefundRead,
},
req.headers(),
),
@@ -507,8 +498,7 @@ pub async fn get_refunds_aggregate_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RefundRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRefundRead,
},
req.headers(),
),
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 4c8d89fa87d..3e0355a884a 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -5,7 +5,6 @@
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,
@@ -44,15 +43,13 @@ pub async fn routing_create_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -87,15 +84,13 @@ pub async fn routing_link_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -137,16 +132,14 @@ pub async fn routing_link_config(
&auth::ApiKeyAuth,
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -180,15 +173,13 @@ pub async fn routing_retrieve_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -222,15 +213,13 @@ pub async fn list_routing_configs(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -264,15 +253,13 @@ pub async fn list_routing_configs_for_profile(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -308,16 +295,14 @@ pub async fn routing_unlink_config(
&auth::ApiKeyAuth,
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -352,15 +337,13 @@ pub async fn routing_unlink_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -397,15 +380,13 @@ pub async fn routing_update_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -437,15 +418,13 @@ pub async fn routing_update_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -478,16 +457,14 @@ pub async fn routing_retrieve_default_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: path,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -513,15 +490,13 @@ pub async fn routing_retrieve_default_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -553,15 +528,13 @@ pub async fn upsert_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -590,15 +563,13 @@ pub async fn delete_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -627,15 +598,13 @@ pub async fn retrieve_surcharge_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantSurchargeDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -667,15 +636,13 @@ pub async fn upsert_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -705,15 +672,13 @@ pub async fn delete_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -739,15 +704,13 @@ pub async fn retrieve_decision_manager_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::SurchargeDecisionManagerRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantThreeDsDecisionManagerRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -786,16 +749,14 @@ pub async fn routing_retrieve_linked_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -820,15 +781,13 @@ pub async fn routing_retrieve_linked_config(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -871,16 +830,14 @@ pub async fn routing_retrieve_linked_config(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -911,8 +868,7 @@ pub async fn routing_retrieve_default_config_for_profiles(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
@@ -920,8 +876,7 @@ pub async fn routing_retrieve_default_config_for_profiles(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::RoutingRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantRoutingRead,
},
req.headers(),
),
@@ -963,16 +918,14 @@ pub async fn routing_update_default_config_for_profile(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
#[cfg(feature = "release")]
&auth::JWTAuthProfileFromRoute {
profile_id: routing_payload_wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -1013,8 +966,7 @@ pub async fn toggle_success_based_routing(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuthProfileFromRoute {
profile_id: wrapper.profile_id,
- required_permission: Permission::RoutingWrite,
- minimum_entity_level: EntityType::Profile,
+ required_permission: Permission::ProfileRoutingWrite,
},
req.headers(),
),
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index e07a2fa10ef..f52d0dca7a8 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::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use common_utils::errors::ReportSwitchExt;
use router_env::Flow;
@@ -176,8 +176,7 @@ pub async fn set_dashboard_metadata(
payload,
user_core::dashboard_metadata::set_metadata,
&auth::JWTAuth {
- permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -243,8 +242,7 @@ pub async fn user_merchant_account_create(
user_core::create_merchant_account(state, auth, json_payload)
},
&auth::JWTAuth {
- permission: Permission::MerchantAccountCreate,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::OrganizationAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -267,8 +265,7 @@ pub async fn generate_sample_data(
payload.into_inner(),
sample_data::generate_sample_data_for_user,
&auth::JWTAuth {
- permission: Permission::PaymentWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantPaymentWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -292,7 +289,6 @@ pub async fn delete_sample_data(
sample_data::delete_sample_data_for_user,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Merchant,
},
api_locking::LockAction::NotApplicable,
))
@@ -312,8 +308,7 @@ pub async fn list_user_roles_details(
payload.into_inner(),
user_core::list_user_roles_details,
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -395,8 +390,7 @@ pub async fn invite_multiple_user(
user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone())
},
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -421,8 +415,7 @@ pub async fn resend_invite(
user_core::resend_invite(state, user, req_payload, auth_id.clone())
},
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -504,8 +497,7 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques
(),
|state, user, _req, _| user_core::verify_token(state, user),
&auth::JWTAuth {
- permission: Permission::ReconAdmin,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantReconWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 777cbe1fd95..74847f06474 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::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use router_env::Flow;
use super::AppState;
@@ -31,8 +31,7 @@ pub async fn get_authorization_info(
user_role_core::get_authorization_info_with_groups(state).await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -69,8 +68,7 @@ pub async fn create_role(
json_payload.into_inner(),
role_core::create_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -95,8 +93,7 @@ pub async fn get_role(
role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -119,8 +116,7 @@ pub async fn update_role(
json_payload.into_inner(),
|state, user, req, _| role_core::update_role(state, user, req, &role_id),
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -141,8 +137,7 @@ pub async fn update_user_role(
payload,
user_role_core::update_user_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -202,8 +197,7 @@ pub async fn delete_user_role(
payload.into_inner(),
user_role_core::delete_user_role,
&auth::JWTAuth {
- permission: Permission::UsersWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserWrite,
},
api_locking::LockAction::NotApplicable,
))
@@ -225,8 +219,7 @@ pub async fn get_role_information(
user_role_core::get_authorization_info_with_group_tag().await
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -270,8 +263,7 @@ pub async fn list_roles_with_info(
role_core::list_roles_with_info(state, user_from_token, request)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -299,8 +291,7 @@ pub async fn list_invitable_roles_at_entity_level(
)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
@@ -328,8 +319,7 @@ pub async fn list_updatable_roles_at_entity_level(
)
},
&auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index 17c946c4810..56ad42947c2 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -1,6 +1,5 @@
use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -34,8 +33,7 @@ pub async fn apple_pay_merchant_registration(
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
- permission: Permission::MerchantAccountWrite,
- minimum_entity_level: EntityType::Profile,
+ permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
@@ -70,7 +68,6 @@ pub async fn retrieve_apple_pay_verified_domains(
&auth::HeaderAuth(auth::ApiKeyAuth),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
- minimum_entity_level: EntityType::Merchant,
},
req.headers(),
),
diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs
index 29f8c154bc0..b8e089f0660 100644
--- a/crates/router/src/routes/verify_connector.rs
+++ b/crates/router/src/routes/verify_connector.rs
@@ -1,6 +1,5 @@
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;
@@ -25,8 +24,7 @@ pub async fn payment_connector_verify(
verify_connector::verify_connector_credentials(state, req, auth.profile_id)
},
&auth::JWTAuth {
- permission: Permission::MerchantConnectorAccountWrite,
- minimum_entity_level: EntityType::Merchant,
+ permission: Permission::MerchantConnectorWrite,
},
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs
index 8b94fb61f56..5039f72db31 100644
--- a/crates/router/src/routes/webhook_events.rs
+++ b/crates/router/src/routes/webhook_events.rs
@@ -1,5 +1,4 @@
use actix_web::{web, HttpRequest, Responder};
-use common_enums::EntityType;
use router_env::{instrument, tracing, Flow};
use crate::{
@@ -44,8 +43,7 @@ pub async fn list_initial_webhook_delivery_attempts(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
@@ -84,8 +82,7 @@ pub async fn list_webhook_delivery_attempts(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventRead,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
@@ -124,8 +121,7 @@ pub async fn retry_webhook_delivery_attempt(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
- required_permission: Permission::WebhookEventWrite,
- minimum_entity_level: EntityType::Merchant,
+ required_permission: Permission::MerchantWebhookEventWrite,
},
req.headers(),
),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b64c5d14f32..e6da2b23301 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::{EntityType, TokenPurpose};
+use common_enums::TokenPurpose;
use common_utils::{date_time, id_type};
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
@@ -1232,7 +1232,6 @@ where
#[derive(Debug)]
pub(crate) struct JWTAuth {
pub permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1252,7 +1251,6 @@ where
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((
(),
@@ -1282,7 +1280,6 @@ where
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 {
@@ -1318,7 +1315,6 @@ where
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
@@ -1359,7 +1355,6 @@ where
pub struct JWTAuthOrganizationFromRoute {
pub organization_id: id_type::OrganizationId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1379,7 +1374,6 @@ where
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 {
@@ -1398,12 +1392,10 @@ 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]
@@ -1423,7 +1415,6 @@ where
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_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
@@ -1459,7 +1450,6 @@ where
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_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
@@ -1526,7 +1516,6 @@ where
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 {
@@ -1563,7 +1552,6 @@ where
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
@@ -1606,7 +1594,6 @@ 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]
@@ -1638,7 +1625,6 @@ where
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
@@ -1682,7 +1668,6 @@ where
pub struct JWTAuthProfileFromRoute {
pub profile_id: id_type::ProfileId,
pub required_permission: Permission,
- pub minimum_entity_level: EntityType,
}
#[async_trait]
@@ -1702,7 +1687,6 @@ where
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
@@ -1798,7 +1782,6 @@ where
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
@@ -1859,7 +1842,6 @@ where
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
@@ -1923,7 +1905,6 @@ where
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
@@ -2349,7 +2330,6 @@ where
}
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
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index 78af4c00884..fe6ffac6ffc 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -112,18 +112,6 @@ pub fn check_permission(
)
}
-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/info.rs b/crates/router/src/services/authorization/info.rs
index 031e0b56729..dba96dac188 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,5 +1,5 @@
-use api_models::user_role::{GroupInfo, ParentGroup};
-use common_enums::PermissionGroup;
+use api_models::user_role::GroupInfo;
+use common_enums::{ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index aafc9cee943..3d1a0c8ea5b 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -1,97 +1,122 @@
-use common_enums::PermissionGroup;
-
-use super::permissions::Permission;
-
-pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission] {
- match permission_group {
- PermissionGroup::OperationsView => &OPERATIONS_VIEW,
- PermissionGroup::OperationsManage => &OPERATIONS_MANAGE,
- PermissionGroup::ConnectorsView => &CONNECTORS_VIEW,
- PermissionGroup::ConnectorsManage => &CONNECTORS_MANAGE,
- PermissionGroup::WorkflowsView => &WORKFLOWS_VIEW,
- PermissionGroup::WorkflowsManage => &WORKFLOWS_MANAGE,
- PermissionGroup::AnalyticsView => &ANALYTICS_VIEW,
- PermissionGroup::UsersView => &USERS_VIEW,
- PermissionGroup::UsersManage => &USERS_MANAGE,
- PermissionGroup::MerchantDetailsView => &MERCHANT_DETAILS_VIEW,
- PermissionGroup::MerchantDetailsManage => &MERCHANT_DETAILS_MANAGE,
- PermissionGroup::OrganizationManage => &ORGANIZATION_MANAGE,
- PermissionGroup::ReconOps => &RECON,
- }
+use common_enums::{ParentGroup, PermissionGroup, PermissionScope, Resource};
+
+pub trait PermissionGroupExt {
+ fn scope(&self) -> PermissionScope;
+ fn parent(&self) -> ParentGroup;
+ fn resources(&self) -> Vec<Resource>;
+ fn accessible_groups(&self) -> Vec<PermissionGroup>;
}
-pub static OPERATIONS_VIEW: [Permission; 8] = [
- Permission::PaymentRead,
- Permission::RefundRead,
- Permission::MandateRead,
- Permission::DisputeRead,
- Permission::CustomerRead,
- Permission::GenerateReport,
- Permission::PayoutRead,
- Permission::MerchantAccountRead,
-];
+impl PermissionGroupExt for PermissionGroup {
+ fn scope(&self) -> PermissionScope {
+ match self {
+ Self::OperationsView
+ | Self::ConnectorsView
+ | Self::WorkflowsView
+ | Self::AnalyticsView
+ | Self::UsersView
+ | Self::MerchantDetailsView => PermissionScope::Read,
-pub static OPERATIONS_MANAGE: [Permission; 7] = [
- Permission::PaymentWrite,
- Permission::RefundWrite,
- Permission::MandateWrite,
- Permission::DisputeWrite,
- Permission::CustomerWrite,
- Permission::PayoutWrite,
- Permission::MerchantAccountRead,
-];
+ Self::OperationsManage
+ | Self::ConnectorsManage
+ | Self::WorkflowsManage
+ | Self::UsersManage
+ | Self::MerchantDetailsManage
+ | Self::OrganizationManage
+ | Self::ReconOps => PermissionScope::Write,
+ }
+ }
-pub static CONNECTORS_VIEW: [Permission; 2] = [
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ fn parent(&self) -> ParentGroup {
+ match self {
+ Self::OperationsView | Self::OperationsManage => ParentGroup::Operations,
+ Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors,
+ Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
+ Self::AnalyticsView => ParentGroup::Analytics,
+ Self::UsersView | Self::UsersManage => ParentGroup::Users,
+ Self::MerchantDetailsView | Self::MerchantDetailsManage => ParentGroup::Merchant,
+ Self::OrganizationManage => ParentGroup::Organization,
+ Self::ReconOps => ParentGroup::Recon,
+ }
+ }
-pub static CONNECTORS_MANAGE: [Permission; 2] = [
- Permission::MerchantConnectorAccountWrite,
- Permission::MerchantAccountRead,
-];
+ fn resources(&self) -> Vec<Resource> {
+ self.parent().resources()
+ }
-pub static WORKFLOWS_VIEW: [Permission; 5] = [
- Permission::RoutingRead,
- Permission::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerRead,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ fn accessible_groups(&self) -> Vec<Self> {
+ match self {
+ Self::OperationsView => vec![Self::OperationsView],
+ Self::OperationsManage => vec![Self::OperationsView, Self::OperationsManage],
-pub static WORKFLOWS_MANAGE: [Permission; 5] = [
- Permission::RoutingWrite,
- Permission::ThreeDsDecisionManagerWrite,
- Permission::SurchargeDecisionManagerWrite,
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantAccountRead,
-];
+ Self::ConnectorsView => vec![Self::ConnectorsView],
+ Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
-pub static ANALYTICS_VIEW: [Permission; 3] = [
- Permission::Analytics,
- Permission::GenerateReport,
- Permission::MerchantAccountRead,
-];
+ Self::WorkflowsView => vec![Self::WorkflowsView],
+ Self::WorkflowsManage => vec![Self::WorkflowsView, Self::WorkflowsManage],
+
+ Self::AnalyticsView => vec![Self::AnalyticsView],
-pub static USERS_VIEW: [Permission; 2] = [Permission::UsersRead, Permission::MerchantAccountRead];
+ Self::UsersView => vec![Self::UsersView],
+ Self::UsersManage => {
+ vec![Self::UsersView, Self::UsersManage]
+ }
-pub static USERS_MANAGE: [Permission; 2] =
- [Permission::UsersWrite, Permission::MerchantAccountRead];
+ Self::ReconOps => vec![Self::ReconOps],
-pub static MERCHANT_DETAILS_VIEW: [Permission; 1] = [Permission::MerchantAccountRead];
+ Self::MerchantDetailsView => vec![Self::MerchantDetailsView],
+ Self::MerchantDetailsManage => {
+ vec![Self::MerchantDetailsView, Self::MerchantDetailsManage]
+ }
-pub static MERCHANT_DETAILS_MANAGE: [Permission; 6] = [
- Permission::MerchantAccountWrite,
- Permission::ApiKeyRead,
- Permission::ApiKeyWrite,
- Permission::MerchantAccountRead,
- Permission::WebhookEventRead,
- Permission::WebhookEventWrite,
+ Self::OrganizationManage => vec![Self::OrganizationManage],
+ }
+ }
+}
+
+pub trait ParentGroupExt {
+ fn resources(&self) -> Vec<Resource>;
+}
+
+impl ParentGroupExt for ParentGroup {
+ fn resources(&self) -> Vec<Resource> {
+ match self {
+ Self::Operations => OPERATIONS.to_vec(),
+ Self::Connectors => CONNECTORS.to_vec(),
+ Self::Workflows => WORKFLOWS.to_vec(),
+ Self::Analytics => ANALYTICS.to_vec(),
+ Self::Users => USERS.to_vec(),
+ Self::Merchant | Self::Organization => ACCOUNT.to_vec(),
+ Self::Recon => RECON.to_vec(),
+ }
+ }
+}
+
+pub static OPERATIONS: [Resource; 8] = [
+ Resource::Payment,
+ Resource::Refund,
+ Resource::Mandate,
+ Resource::Dispute,
+ Resource::Customer,
+ Resource::Payout,
+ Resource::Report,
+ Resource::Account,
];
-pub static ORGANIZATION_MANAGE: [Permission; 2] = [
- Permission::MerchantAccountCreate,
- Permission::MerchantAccountRead,
+pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account];
+
+pub static WORKFLOWS: [Resource; 5] = [
+ Resource::Routing,
+ Resource::ThreeDsDecisionManager,
+ Resource::SurchargeDecisionManager,
+ Resource::Connector,
+ Resource::Account,
];
-pub static RECON: [Permission; 1] = [Permission::ReconAdmin];
+pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account];
+
+pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];
+
+pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];
+
+pub static RECON: [Resource; 1] = [Resource::Recon];
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 2121ba0f944..0521db7acc1 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -1,39 +1,75 @@
-use strum::Display;
+use common_enums::{EntityType, PermissionScope, Resource};
+use router_derive::generate_permissions;
-#[derive(
- PartialEq, Display, Clone, Debug, Copy, Eq, Hash, serde::Deserialize, serde::Serialize,
-)]
-pub enum Permission {
- PaymentRead,
- PaymentWrite,
- RefundRead,
- RefundWrite,
- ApiKeyRead,
- ApiKeyWrite,
- MerchantAccountRead,
- MerchantAccountWrite,
- MerchantConnectorAccountRead,
- MerchantConnectorAccountWrite,
- RoutingRead,
- RoutingWrite,
- DisputeRead,
- DisputeWrite,
- MandateRead,
- MandateWrite,
- CustomerRead,
- CustomerWrite,
- Analytics,
- ThreeDsDecisionManagerWrite,
- ThreeDsDecisionManagerRead,
- SurchargeDecisionManagerWrite,
- SurchargeDecisionManagerRead,
- UsersRead,
- UsersWrite,
- MerchantAccountCreate,
- WebhookEventRead,
- WebhookEventWrite,
- PayoutRead,
- PayoutWrite,
- GenerateReport,
- ReconAdmin,
+generate_permissions! {
+ permissions: [
+ Payment: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Refund: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Dispute: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Mandate: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Customer: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Payout: {
+ scopes: [Read],
+ entities: [Profile, Merchant]
+ },
+ ApiKey: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Account: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant, Organization]
+ },
+ Connector: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ Routing: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ ThreeDsDecisionManager: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ SurchargeDecisionManager: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Analytics: {
+ scopes: [Read],
+ entities: [Profile, Merchant, Organization]
+ },
+ Report: {
+ scopes: [Read],
+ entities: [Profile, Merchant, Organization]
+ },
+ User: {
+ scopes: [Read, Write],
+ entities: [Profile, Merchant]
+ },
+ WebhookEvent: {
+ scopes: [Read, Write],
+ entities: [Merchant]
+ },
+ Recon: {
+ scopes: [Write],
+ entities: [Merchant]
+ },
+ ]
}
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 19383f010f2..63d547bfa67 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -1,9 +1,9 @@
use std::collections::HashSet;
-use common_enums::{EntityType, PermissionGroup, RoleScope};
+use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
-use super::{permission_groups::get_permissions_vec, permissions::Permission};
+use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
@@ -30,8 +30,13 @@ impl RoleInfo {
&self.role_name
}
- pub fn get_permission_groups(&self) -> &Vec<PermissionGroup> {
- &self.groups
+ pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
+ self.groups
+ .iter()
+ .flat_map(|group| group.accessible_groups())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect()
}
pub fn get_scope(&self) -> RoleScope {
@@ -58,17 +63,19 @@ impl RoleInfo {
self.is_updatable
}
- pub fn get_permissions_set(&self) -> HashSet<Permission> {
- self.groups
+ pub fn get_resources_set(&self) -> HashSet<Resource> {
+ self.get_permission_groups()
.iter()
- .flat_map(|group| get_permissions_vec(group).iter().copied())
+ .flat_map(|group| group.resources())
.collect()
}
pub fn check_permission_exists(&self, required_permission: &Permission) -> bool {
- self.groups
- .iter()
- .any(|group| get_permissions_vec(group).contains(required_permission))
+ required_permission.entity_type() <= self.entity_type
+ && self.get_permission_groups().iter().any(|group| {
+ required_permission.scope() <= group.scope()
+ && group.resources().contains(&required_permission.resource())
+ })
}
pub async fn from_role_id_in_merchant_scope(
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs
index 02179934e38..69865512a37 100644
--- a/crates/router_derive/src/lib.rs
+++ b/crates/router_derive/src/lib.rs
@@ -694,3 +694,58 @@ pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenSt
proc_macro::TokenStream::from(expanded)
}
+
+/// Generates the permissions enum and implematations for the permissions
+///
+/// **NOTE:** You have to make sure that all the identifiers used
+/// in the macro input are present in the respective enums as well.
+///
+/// ## Usage
+/// ```
+/// use router_derive::generate_permissions;
+///
+/// enum Scope {
+/// Read,
+/// Write,
+/// }
+///
+/// enum EntityType {
+/// Profile,
+/// Merchant,
+/// Org,
+/// }
+///
+/// enum Resource {
+/// Payments,
+/// Refunds,
+/// }
+///
+/// generate_permissions! {
+/// permissions: [
+/// Payments: {
+/// scopes: [Read, Write],
+/// entities: [Profile, Merchant, Org]
+/// },
+/// Refunds: {
+/// scopes: [Read],
+/// entities: [Profile, Org]
+/// }
+/// ]
+/// }
+/// ```
+/// This will generate the following enum.
+/// ```
+/// enum Permission {
+/// ProfilePaymentsRead,
+/// ProfilePaymentsWrite,
+/// MerchantPaymentsRead,
+/// MerchantPaymentsWrite,
+/// OrgPaymentsRead,
+/// OrgPaymentsWrite,
+/// ProfileRefundsRead,
+/// OrgRefundsRead,
+/// ```
+#[proc_macro]
+pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ macros::generate_permissions_inner(input)
+}
diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs
index 9a8e514c5c1..32e6c213ca6 100644
--- a/crates/router_derive/src/macros.rs
+++ b/crates/router_derive/src/macros.rs
@@ -1,5 +1,6 @@
pub(crate) mod api_error;
pub(crate) mod diesel;
+pub(crate) mod generate_permissions;
pub(crate) mod generate_schema;
pub(crate) mod misc;
pub(crate) mod operation;
@@ -14,6 +15,7 @@ use syn::DeriveInput;
pub(crate) use self::{
api_error::api_error_derive_inner,
diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner},
+ generate_permissions::generate_permissions_inner,
generate_schema::polymorphic_macro_derive_inner,
};
diff --git a/crates/router_derive/src/macros/generate_permissions.rs b/crates/router_derive/src/macros/generate_permissions.rs
new file mode 100644
index 00000000000..9b388f102cb
--- /dev/null
+++ b/crates/router_derive/src/macros/generate_permissions.rs
@@ -0,0 +1,135 @@
+use proc_macro::TokenStream;
+use quote::{format_ident, quote};
+use syn::{
+ braced, bracketed,
+ parse::{Parse, ParseBuffer, ParseStream},
+ parse_macro_input,
+ punctuated::Punctuated,
+ token::Comma,
+ Ident, Token,
+};
+
+struct ResourceInput {
+ resource_name: Ident,
+ scopes: Punctuated<Ident, Token![,]>,
+ entities: Punctuated<Ident, Token![,]>,
+}
+
+struct Input {
+ permissions: Punctuated<ResourceInput, Token![,]>,
+}
+
+impl Parse for Input {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let (_permission_label, permissions) = parse_label_with_punctuated_data(input)?;
+
+ Ok(Self { permissions })
+ }
+}
+
+impl Parse for ResourceInput {
+ fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
+ let resource_name: Ident = input.parse()?;
+ input.parse::<Token![:]>()?; // Expect ':'
+
+ let content;
+ braced!(content in input);
+
+ let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?;
+ content.parse::<Comma>()?;
+
+ let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?;
+
+ Ok(Self {
+ resource_name,
+ scopes,
+ entities,
+ })
+ }
+}
+
+fn parse_label_with_punctuated_data<T: Parse>(
+ input: &ParseBuffer<'_>,
+) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> {
+ let label: Ident = input.parse()?;
+ input.parse::<Token![:]>()?; // Expect ':'
+
+ let content;
+ bracketed!(content in input); // Parse the list inside []
+ let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?;
+
+ Ok((label, data))
+}
+
+pub fn generate_permissions_inner(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as Input);
+
+ let res = input.permissions.iter();
+
+ let mut enum_keys = Vec::new();
+ let mut scope_impl_per = Vec::new();
+ let mut entity_impl_per = Vec::new();
+ let mut resource_impl_per = Vec::new();
+
+ let mut entity_impl_res = Vec::new();
+
+ for per in res {
+ let resource_name = &per.resource_name;
+ let mut permissions = Vec::new();
+
+ for scope in per.scopes.iter() {
+ for entity in per.entities.iter() {
+ let key = format_ident!("{}{}{}", entity, per.resource_name, scope);
+
+ enum_keys.push(quote! { #key });
+ scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope });
+ entity_impl_per.push(quote! { Permission::#key => EntityType::#entity });
+ resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name });
+ permissions.push(quote! { Permission::#key });
+ }
+ let entities_iter = per.entities.iter();
+ entity_impl_res
+ .push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] });
+ }
+ }
+
+ let expanded = quote! {
+ #[derive(
+ Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display
+ )]
+ pub enum Permission {
+ #(#enum_keys),*
+ }
+
+ impl Permission {
+ pub fn scope(&self) -> PermissionScope {
+ match self {
+ #(#scope_impl_per),*
+ }
+ }
+ pub fn entity_type(&self) -> EntityType {
+ match self {
+ #(#entity_impl_per),*
+ }
+ }
+ pub fn resource(&self) -> Resource {
+ match self {
+ #(#resource_impl_per),*
+ }
+ }
+ }
+
+ pub trait ResourceExt {
+ fn entities(&self) -> Vec<EntityType>;
+ }
+
+ impl ResourceExt for Resource {
+ fn entities(&self) -> Vec<EntityType> {
+ match self {
+ #(#entity_impl_res),*
+ }
+ }
+ }
+ };
+ expanded.into()
+}
|
2024-10-22T12:12:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Entity level context in Permissions
Currently the permissions we use doesn't have any entity level context. But some of our APIs need that context.
For example,
1. `payment/list` - This can only be accessible by merchant level users or higher. Profile level users should not be able to access it.
2. `payment/profile/list` - This can be accessible by all level of users.
With current setup, this is not directly possible by the permissions. We had to introduce `min_entity_level` to solve this, but this is very separated from the permissions.
To solve this, we need to have entity level context at permissions level itself.
### Scope for permissions
The write permissions currently doesn't have access to read APIs, but since write is a superset of read, they should be able to access read APIs as well.
So, this PR also introduces scope context in permissions.
---
This PR also improves the scalability of permissions, as the more entity levels being added in the control center, this will make it easy to extend the permissions as well.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies 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).
-->
Closes [#6391](https://github.com/juspay/hyperswitch/issues/6391).
## How did you test 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 is an internal change, no APIs should be affected and all the APIs should be working as usual.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c7c1e1adabceeb0a03659bf8feb9aa06d85960ea
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6375
|
Bug: refactor(permissions): Deprecate permissions from permission info API response
The permissions in the permission info API are not being used and should be removed.
|
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index ab32651e729..e64639646d1 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -4,42 +4,6 @@ use masking::Secret;
pub mod role;
-#[derive(Debug, serde::Serialize)]
-pub enum Permission {
- PaymentRead,
- PaymentWrite,
- RefundRead,
- RefundWrite,
- ApiKeyRead,
- ApiKeyWrite,
- MerchantAccountRead,
- MerchantAccountWrite,
- MerchantConnectorAccountRead,
- MerchantConnectorAccountWrite,
- RoutingRead,
- RoutingWrite,
- DisputeRead,
- DisputeWrite,
- MandateRead,
- MandateWrite,
- CustomerRead,
- CustomerWrite,
- Analytics,
- ThreeDsDecisionManagerWrite,
- ThreeDsDecisionManagerRead,
- SurchargeDecisionManagerWrite,
- SurchargeDecisionManagerRead,
- UsersRead,
- UsersWrite,
- MerchantAccountCreate,
- WebhookEventRead,
- PayoutWrite,
- PayoutRead,
- WebhookEventWrite,
- GenerateReport,
- ReconAdmin,
-}
-
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash)]
pub enum ParentGroup {
Operations,
@@ -69,7 +33,6 @@ pub enum AuthorizationInfo {
pub struct GroupInfo {
pub group: PermissionGroup,
pub description: &'static str,
- pub permissions: Vec<PermissionInfo>,
}
#[derive(Debug, serde::Serialize, Clone)]
@@ -79,12 +42,6 @@ pub struct ParentInfo {
pub groups: Vec<PermissionGroup>,
}
-#[derive(Debug, serde::Serialize)]
-pub struct PermissionInfo {
- pub enum_name: Permission,
- pub description: &'static str,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserRoleRequest {
pub email: pii::Email,
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 7cfde3efeea..031e0b56729 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,9 +1,7 @@
-use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo};
+use api_models::user_role::{GroupInfo, ParentGroup};
use common_enums::PermissionGroup;
use strum::IntoEnumIterator;
-use super::{permission_groups::get_permissions_vec, permissions::Permission};
-
// TODO: To be deprecated
pub fn get_group_authorization_info() -> Vec<GroupInfo> {
PermissionGroup::iter()
@@ -11,25 +9,10 @@ pub fn get_group_authorization_info() -> Vec<GroupInfo> {
.collect()
}
-// TODO: To be deprecated
-pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> {
- permissions
- .iter()
- .map(|&per| PermissionInfo {
- description: Permission::get_permission_description(&per),
- enum_name: per.into(),
- })
- .collect()
-}
-
// TODO: To be deprecated
fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
let description = get_group_description(group);
- GroupInfo {
- group,
- description,
- permissions: get_permission_info_from_permissions(get_permissions_vec(&group)),
- }
+ GroupInfo { group, description }
}
// TODO: To be deprecated
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 2f0617557ca..2121ba0f944 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -37,48 +37,3 @@ pub enum Permission {
GenerateReport,
ReconAdmin,
}
-
-impl Permission {
- pub fn get_permission_description(&self) -> &'static str {
- match self {
- Self::PaymentRead => "View all payments",
- Self::PaymentWrite => "Create payment, download payments data",
- Self::RefundRead => "View all refunds",
- Self::RefundWrite => "Create refund, download refunds data",
- Self::ApiKeyRead => "View API keys",
- Self::ApiKeyWrite => "Create and update API keys",
- Self::MerchantAccountRead => "View merchant account details",
- Self::MerchantAccountWrite => {
- "Update merchant account details, configure webhooks, manage api keys"
- }
- Self::MerchantConnectorAccountRead => "View connectors configured",
- Self::MerchantConnectorAccountWrite => {
- "Create, update, verify and delete connector configurations"
- }
- Self::RoutingRead => "View routing configuration",
- Self::RoutingWrite => "Create and activate routing configurations",
- Self::DisputeRead => "View disputes",
- Self::DisputeWrite => "Create and update disputes",
- Self::MandateRead => "View mandates",
- Self::MandateWrite => "Create and update mandates",
- Self::CustomerRead => "View customers",
- Self::CustomerWrite => "Create, update and delete customers",
- Self::Analytics => "Access to analytics module",
- Self::ThreeDsDecisionManagerWrite => "Create and update 3DS decision rules",
- Self::ThreeDsDecisionManagerRead => {
- "View all 3DS decision rules configured for a merchant"
- }
- Self::SurchargeDecisionManagerWrite => "Create and update the surcharge decision rules",
- Self::SurchargeDecisionManagerRead => "View all the surcharge decision rules",
- Self::UsersRead => "View all the users for a merchant",
- Self::UsersWrite => "Invite users, assign and update roles",
- Self::MerchantAccountCreate => "Create merchant account",
- Self::WebhookEventRead => "View webhook events",
- Self::WebhookEventWrite => "Trigger retries for webhook events",
- Self::PayoutRead => "View all payouts",
- Self::PayoutWrite => "Create payout, download payout data",
- Self::GenerateReport => "Generate reports for payments, refunds and disputes",
- Self::ReconAdmin => "View and manage reconciliation reports",
- }
- }
-}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 0ea423989f5..6f0d94d2927 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,6 +1,5 @@
use std::{cmp, collections::HashSet};
-use api_models::user_role as user_role_api;
use common_enums::{EntityType, PermissionGroup};
use common_utils::id_type;
use diesel_models::{
@@ -16,49 +15,10 @@ use crate::{
core::errors::{UserErrors, UserResult},
db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
routes::SessionState,
- services::authorization::{self as authz, permissions::Permission, roles},
+ services::authorization::{self as authz, roles},
types::domain,
};
-impl From<Permission> for user_role_api::Permission {
- fn from(value: Permission) -> Self {
- match value {
- Permission::PaymentRead => Self::PaymentRead,
- Permission::PaymentWrite => Self::PaymentWrite,
- Permission::RefundRead => Self::RefundRead,
- Permission::RefundWrite => Self::RefundWrite,
- Permission::ApiKeyRead => Self::ApiKeyRead,
- Permission::ApiKeyWrite => Self::ApiKeyWrite,
- Permission::MerchantAccountRead => Self::MerchantAccountRead,
- Permission::MerchantAccountWrite => Self::MerchantAccountWrite,
- Permission::MerchantConnectorAccountRead => Self::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite => Self::MerchantConnectorAccountWrite,
- Permission::RoutingRead => Self::RoutingRead,
- Permission::RoutingWrite => Self::RoutingWrite,
- Permission::DisputeRead => Self::DisputeRead,
- Permission::DisputeWrite => Self::DisputeWrite,
- Permission::MandateRead => Self::MandateRead,
- Permission::MandateWrite => Self::MandateWrite,
- Permission::CustomerRead => Self::CustomerRead,
- Permission::CustomerWrite => Self::CustomerWrite,
- Permission::Analytics => Self::Analytics,
- Permission::ThreeDsDecisionManagerWrite => Self::ThreeDsDecisionManagerWrite,
- Permission::ThreeDsDecisionManagerRead => Self::ThreeDsDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite => Self::SurchargeDecisionManagerWrite,
- Permission::SurchargeDecisionManagerRead => Self::SurchargeDecisionManagerRead,
- Permission::UsersRead => Self::UsersRead,
- Permission::UsersWrite => Self::UsersWrite,
- Permission::MerchantAccountCreate => Self::MerchantAccountCreate,
- Permission::WebhookEventRead => Self::WebhookEventRead,
- Permission::WebhookEventWrite => Self::WebhookEventWrite,
- Permission::PayoutRead => Self::PayoutRead,
- Permission::PayoutWrite => Self::PayoutWrite,
- Permission::GenerateReport => Self::GenerateReport,
- Permission::ReconAdmin => Self::ReconAdmin,
- }
- }
-}
-
pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
if groups.is_empty() {
return Err(report!(UserErrors::InvalidRoleOperation))
|
2024-10-21T06:56:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The permissions in the permission info API are not being used and this PR will remove them.
This will help the future PRs which will introduce new kind of Permissions.
### 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 [#6375](https://github.com/juspay/hyperswitch/issues/6375).
## How did you test 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 'https://sandbox.hyperswitch.io/user/permission_info' \
--header 'Authorization: Bearer JWT'
```
This API will no longer have permissions field in the response.
```json
[
{
"group": "operations_view",
"description": "View Payments, Refunds, Payouts, Mandates, Disputes and Customers"
},
{
"group": "operations_manage",
"description": "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0dba763c3a1c69fa282ffa644a12d37dc14d8f7b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6364
|
Bug: feat(config): update vector config
# Current Behaviour
- Sdk logs pushes `publishable_key` in the `merchant_id` field.
- open search logs have some irrelevant fields.
# Proposed Changes
- transform sdk logs and update the correct corresponding `merchant_id` of the pre-existing `publishable_key` value
- add some more except/ignore fields in open search sinks.
|
diff --git a/config/vector.yaml b/config/vector.yaml
index 3f0709ae03c..4b801935ae5 100644
--- a/config/vector.yaml
+++ b/config/vector.yaml
@@ -1,5 +1,16 @@
acknowledgements:
enabled: true
+enrichment_tables:
+ sdk_map:
+ type: file
+ file:
+ path: /etc/vector/config/sdk_map.csv
+ encoding:
+ type: csv
+ schema:
+ publishable_key: string
+ merchant_id: string
+
api:
enabled: true
@@ -87,6 +98,21 @@ transforms:
key_field: "{{ .payment_id }}{{ .merchant_id }}"
threshold: 1000
window_secs: 60
+
+ amend_sdk_logs:
+ type: remap
+ inputs:
+ - sdk_transformed
+ source: |
+ .before_transform = now()
+
+ merchant_id = .merchant_id
+ row = get_enrichment_table_record!("sdk_map", { "publishable_key" : merchant_id }, case_sensitive: true)
+ .merchant_id = row.merchant_id
+
+ .after_transform = now()
+
+
sinks:
opensearch_events_1:
@@ -110,6 +136,9 @@ sinks:
- offset
- partition
- topic
+ - clickhouse_database
+ - last_synced
+ - sign_flag
bulk:
index: "vector-{{ .topic }}"
@@ -134,6 +163,9 @@ sinks:
- offset
- partition
- topic
+ - clickhouse_database
+ - last_synced
+ - sign_flag
bulk:
# Add a date suffixed index for better grouping
index: "vector-{{ .topic }}-%Y-%m-%d"
@@ -224,7 +256,7 @@ sinks:
- "path"
- "source_type"
inputs:
- - "sdk_transformed"
+ - "amend_sdk_logs"
bootstrap_servers: kafka0:29092
topic: hyper-sdk-logs
key_field: ".merchant_id"
|
2024-10-18T10:13:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Fixes #6364
## Description
<!-- Describe your changes in detail -->
- adding a transform for `sdk` logs that fetches a value from an enrichment table `sdk_map` populated by file `sdk_map.csv` and updates the fields using this value.
- adding some fields to ignore/except in `opensearch` logs sink
**Important Notes**
_Please ensure that the `sdk_map.csv` file is properly formatted and accessible at the specified path. The name of the file should also match the name of the table in config i.e `sdk_map`._
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
### Prior Behaviour
- sdk logs have a merchant_id field but it was being populated with publishable_key as value at source
observed `merchant_id: "pk_dev*****"`.
expected `merchant_id: "merchant_*****"`.
- open search logs have certain fields like `last_synced`, `sign_flag` and `clickhouse_database` that needed to be ignored
### Intentions
- Ensuring correctness of logs and reduce log size by storing only relevant fields.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### Running it locally to check logs added in console (sdk) logs & opensearch
#### sdk_logs
I created a dummy_transform event that inserted a `publishable_key` in merchant_id field and passed it to the actual
transform function and then captured the output on a
[console sink](https://vector.dev/docs/reference/configuration/sinks/console/console)
- test-code
<img width="1156" alt="Screenshot 2024-10-23 at 10 26 22 PM" src="https://github.com/user-attachments/assets/8f22c579-884f-4c65-8b09-aa657e87b261">
- sdk_map.csv (with dummy value 19999)
<img width="828" alt="Screenshot 2024-10-23 at 10 27 26 PM" src="https://github.com/user-attachments/assets/8e5bf34a-b082-451f-94c4-638178bd3e63">
- console output
<img width="1390" alt="Screenshot 2024-10-23 at 10 25 40 PM" src="https://github.com/user-attachments/assets/b126978d-da7a-43b5-bcb4-512bfdf00afb">
#### opensearch logs
for this simply created a payment and compared the logs from kafka topics and opensearch entries
kafka ui
<img width="1726" alt="Screenshot 2024-10-23 at 10 44 45 PM" src="https://github.com/user-attachments/assets/6acfbb66-3d14-4156-9dc9-1d9d261331c7">
opensearch dashboard (no last_synced entry found)
<img width="1708" alt="Screenshot 2024-10-23 at 10 45 43 PM" src="https://github.com/user-attachments/assets/8574306d-4e85-4f79-9c3d-538c0f7aa7ca">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
35bf5a91d9a5b2d5e476c995e679b445242218e0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6363
|
Bug: make `x_merchant_domain` as required value only for session call done on web
The merchant domain url is only required in case of samsung pay payments on web. While processing payments on app the merchant domain is not required. Hence mandate the merchant domain only if the `x-client-platform` is `web`
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 1db9c98806b..654161d1c09 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -19148,7 +19148,6 @@
"type": "object",
"required": [
"name",
- "url",
"country_code"
],
"properties": {
@@ -19158,7 +19157,8 @@
},
"url": {
"type": "string",
- "description": "Merchant domain that process payments"
+ "description": "Merchant domain that process payments, required for web payments",
+ "nullable": true
},
"country_code": {
"$ref": "#/components/schemas/CountryAlpha2"
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 71f383f014e..c28406cf630 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -5500,8 +5500,8 @@ pub enum SamsungPayProtocolType {
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 domain that process payments, required for web payments
+ pub url: Option<String>,
/// Merchant country code
#[schema(value_type = CountryAlpha2, example = "US")]
pub country_code: api_enums::CountryAlpha2,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 49b89fd5623..31027bc8c52 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -550,10 +550,15 @@ fn create_samsung_pay_session_token(
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")?;
+ let merchant_domain = match header_payload.x_client_platform {
+ Some(common_enums::ClientPlatform::Web) => Some(
+ header_payload
+ .x_merchant_domain
+ .get_required_value("samsung pay domain")
+ .attach_printable("Failed to get domain for samsung pay session call")?,
+ ),
+ _ => None,
+ };
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
|
2024-10-18T08:22:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The merchant domain url is only required in case of samsung pay payments on web. While processing payments on app the merchant domain is not required. Hence mandate the merchant domain only if the `x-client-platform` is `web`
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 connector 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: dev_GhK0bBcXMIVjqoKmEip0XbSEvPXOuaEOLlMdBQWL4gdD51LsgHsjj2vzyuxMahw1' \
--data '{
"amount": 100000,
"currency": "USD",
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"confirm": false,
"customer_id": "cu_1728548597"
}'
```
```
{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"merchant_id": "merchant_1729239061",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu",
"created": "2024-10-18T09:06:02.530Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"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_1728548597",
"created_at": 1729242362,
"expires": 1729245962,
"secret": "epk_d521808e21a34868a01d050538f1f602"
},
"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_jh473NMl0nqGqosp7dqW",
"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-18T09:21:02.530Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-18T09:06:02.581Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
-> Session call, pass `x-client-platform` as `web` and `x-merchant-domain` as `sdk-test-app.netlify.app`
```
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_f2a5482b81f34fd884e8efbae5e2598c' \
--data '{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"wallets": [],
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu"
}'
```
```
{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu",
"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": ""
}
}
}
],
"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-rXRkcJK4eiTFnb29Meks",
"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
}
]
}
```
-> Session call, pass `x-client-platform` as `web` and do not pass `x-merchant-domain`. Response will not contain the samsung pay session token.
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: web' \
--header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \
--data '{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"wallets": [],
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu"
}'
```
```
{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu",
"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": "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
}
]
}
```
-> Session call, do not pass `x-client-platform`
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \
--data '{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"wallets": [],
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu"
}'
```
```
{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu",
"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-rXRkcJK4eiTFnb29Meks",
"merchant": {
"name": "Hyperswitch",
"url": null,
"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
}
]
}
```
-> Session call, pass `x-client-platform` as `ios`
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'x-browser-name: Chrome' \
--header 'x-client-platform: ios' \
--header 'api-key: pk_dev_f2a5482b81f34fd884e8efbae5e2598c' \
--data '{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"wallets": [],
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu"
}'
```
```
{
"payment_id": "pay_rXRkcJK4eiTFnb29Meks",
"client_secret": "pay_rXRkcJK4eiTFnb29Meks_secret_OmhCTXdoKth6331TaKJu",
"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-rXRkcJK4eiTFnb29Meks",
"merchant": {
"name": "Hyperswitch",
"url": null,
"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
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
451376e7993839f5c93624c12833af7d47aa4e34
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6357
|
Bug: feat(opensearch): add additional filters and create sessionizer indexes for local
Global search has two components:
- Free flow search, wherein search takes place across all fields available to search upon
- Search on a specific field based on the field filter
Additional filters should be added for global search to search on a specific field.
A list of values can be provided for every filter field which will be added to the query in order to extract responses from opensearch / elasticsearch.
Existing filters (fields):
- payment_method
- currency
- status
- customer_email
- search_tags
New filters to be added (fields):
- connector
- payment_method_type
- card_network
- card_last_4
- payment_id
|
diff --git a/config/config.example.toml b/config/config.example.toml
index c0358d91a26..8f04ba49831 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -728,6 +728,10 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+sessionizer_payment_attempts = "sessionizer-payment-attempt-events"
+sessionizer_payment_intents = "sessionizer-payment-intent-events"
+sessionizer_refunds = "sessionizer-refund-events"
+sessionizer_disputes = "sessionizer-dispute-events"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 5dce5be9c96..cfefe9a130f 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -252,6 +252,10 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+sessionizer_payment_attempts = "sessionizer-payment-attempt-events"
+sessionizer_payment_intents = "sessionizer-payment-intent-events"
+sessionizer_refunds = "sessionizer-refund-events"
+sessionizer_disputes = "sessionizer-dispute-events"
# Configuration for the Key Manager Service
[key_manager]
diff --git a/config/development.toml b/config/development.toml
index 0153c6ef102..29cd2dd048d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -732,6 +732,10 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+sessionizer_payment_attempts = "sessionizer-payment-attempt-events"
+sessionizer_payment_intents = "sessionizer-payment-intent-events"
+sessionizer_refunds = "sessionizer-refund-events"
+sessionizer_disputes = "sessionizer-dispute-events"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 5ffe5df138f..006b017de0b 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -556,6 +556,10 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+sessionizer_payment_attempts = "sessionizer-payment-attempt-events"
+sessionizer_payment_intents = "sessionizer-payment-intent-events"
+sessionizer_refunds = "sessionizer-refund-events"
+sessionizer_disputes = "sessionizer-dispute-events"
[saved_payment_methods]
sdk_eligible_payment_methods = "card"
diff --git a/config/vector.yaml b/config/vector.yaml
index 54ff25cab5a..3f0709ae03c 100644
--- a/config/vector.yaml
+++ b/config/vector.yaml
@@ -18,6 +18,15 @@ sources:
decoding:
codec: json
+ sessionized_kafka_tx_events:
+ type: kafka
+ bootstrap_servers: kafka0:29092
+ group_id: sessionizer
+ topics:
+ - ^sessionizer
+ decoding:
+ codec: json
+
app_logs:
type: docker_logs
include_labels:
@@ -35,10 +44,19 @@ sources:
encoding: json
transforms:
+ events_create_ts:
+ inputs:
+ - kafka_tx_events
+ source: |-
+ .timestamp = from_unix_timestamp(.created_at, unit: "seconds") ?? now()
+ ."@timestamp" = from_unix_timestamp(.created_at, unit: "seconds") ?? now()
+ type: remap
+
plus_1_events:
type: filter
inputs:
- - kafka_tx_events
+ - events_create_ts
+ - sessionized_events_create_ts
condition: ".sign_flag == 1"
hs_server_logs:
@@ -54,13 +72,13 @@ transforms:
source: |-
.message = parse_json!(.message)
- events:
+ sessionized_events_create_ts:
type: remap
inputs:
- - plus_1_events
+ - sessionized_kafka_tx_events
source: |-
- .timestamp = from_unix_timestamp!(.created_at, unit: "seconds")
- ."@timestamp" = from_unix_timestamp(.created_at, unit: "seconds") ?? now()
+ .timestamp = from_unix_timestamp(.created_at, unit: "milliseconds") ?? now()
+ ."@timestamp" = from_unix_timestamp(.created_at, unit: "milliseconds") ?? now()
sdk_transformed:
type: throttle
@@ -74,7 +92,7 @@ sinks:
opensearch_events_1:
type: elasticsearch
inputs:
- - events
+ - plus_1_events
endpoints:
- "https://opensearch:9200"
id_key: message_key
@@ -98,7 +116,7 @@ sinks:
opensearch_events_2:
type: elasticsearch
inputs:
- - events
+ - plus_1_events
endpoints:
- "https://opensearch:9200"
id_key: message_key
@@ -120,6 +138,33 @@ sinks:
# Add a date suffixed index for better grouping
index: "vector-{{ .topic }}-%Y-%m-%d"
+ opensearch_events_3:
+ type: elasticsearch
+ inputs:
+ - plus_1_events
+ endpoints:
+ - "https://opensearch:9200"
+ id_key: message_key
+ api_version: v7
+ tls:
+ verify_certificate: false
+ verify_hostname: false
+ auth:
+ strategy: basic
+ user: admin
+ password: 0penS3arc#
+ encoding:
+ except_fields:
+ - message_key
+ - offset
+ - partition
+ - topic
+ - clickhouse_database
+ - last_synced
+ - sign_flag
+ bulk:
+ index: "{{ .topic }}"
+
opensearch_logs:
type: elasticsearch
inputs:
@@ -143,6 +188,7 @@ sinks:
type: loki
inputs:
- kafka_tx_events
+ - sessionized_kafka_tx_events
endpoint: http://loki:3100
labels:
source: vector
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 3be9688d8f7..a6e6c486ebe 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -42,6 +42,10 @@ pub struct OpenSearchIndexes {
pub payment_intents: String,
pub refunds: String,
pub disputes: String,
+ pub sessionizer_payment_attempts: String,
+ pub sessionizer_payment_intents: String,
+ pub sessionizer_refunds: String,
+ pub sessionizer_disputes: String,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash)]
@@ -81,6 +85,10 @@ impl Default for OpenSearchConfig {
payment_intents: "hyperswitch-payment-intent-events".to_string(),
refunds: "hyperswitch-refund-events".to_string(),
disputes: "hyperswitch-dispute-events".to_string(),
+ sessionizer_payment_attempts: "sessionizer-payment-attempt-events".to_string(),
+ sessionizer_payment_intents: "sessionizer-payment-intent-events".to_string(),
+ sessionizer_refunds: "sessionizer-refund-events".to_string(),
+ sessionizer_disputes: "sessionizer-dispute-events".to_string(),
},
}
}
@@ -219,6 +227,14 @@ impl OpenSearchClient {
SearchIndex::PaymentIntents => self.indexes.payment_intents.clone(),
SearchIndex::Refunds => self.indexes.refunds.clone(),
SearchIndex::Disputes => self.indexes.disputes.clone(),
+ SearchIndex::SessionizerPaymentAttempts => {
+ self.indexes.sessionizer_payment_attempts.clone()
+ }
+ SearchIndex::SessionizerPaymentIntents => {
+ self.indexes.sessionizer_payment_intents.clone()
+ }
+ SearchIndex::SessionizerRefunds => self.indexes.sessionizer_refunds.clone(),
+ SearchIndex::SessionizerDisputes => self.indexes.sessionizer_disputes.clone(),
}
}
@@ -324,6 +340,36 @@ impl OpenSearchIndexes {
))
})?;
+ when(
+ self.sessionizer_payment_attempts.is_default_or_empty(),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Sessionizer Payment Attempts index must not be empty".into(),
+ ))
+ },
+ )?;
+
+ when(
+ self.sessionizer_payment_intents.is_default_or_empty(),
+ || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Sessionizer Payment Intents index must not be empty".into(),
+ ))
+ },
+ )?;
+
+ when(self.sessionizer_refunds.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Sessionizer Refunds index must not be empty".into(),
+ ))
+ })?;
+
+ when(self.sessionizer_disputes.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Opensearch Sessionizer Disputes index must not be empty".into(),
+ ))
+ })?;
+
Ok(())
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index c81ff2f416b..f53b07b1232 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -92,6 +92,44 @@ pub async fn msearch_results(
.switch()?;
}
};
+ if let Some(connector) = filters.connector {
+ if !connector.is_empty() {
+ query_builder
+ .add_filter_clause("connector.keyword".to_string(), connector.clone())
+ .switch()?;
+ }
+ };
+ if let Some(payment_method_type) = filters.payment_method_type {
+ if !payment_method_type.is_empty() {
+ query_builder
+ .add_filter_clause(
+ "payment_method_type.keyword".to_string(),
+ payment_method_type.clone(),
+ )
+ .switch()?;
+ }
+ };
+ if let Some(card_network) = filters.card_network {
+ if !card_network.is_empty() {
+ query_builder
+ .add_filter_clause("card_network.keyword".to_string(), card_network.clone())
+ .switch()?;
+ }
+ };
+ if let Some(card_last_4) = filters.card_last_4 {
+ if !card_last_4.is_empty() {
+ query_builder
+ .add_filter_clause("card_last_4.keyword".to_string(), card_last_4.clone())
+ .switch()?;
+ }
+ };
+ if let Some(payment_id) = filters.payment_id {
+ if !payment_id.is_empty() {
+ query_builder
+ .add_filter_clause("payment_id.keyword".to_string(), payment_id.clone())
+ .switch()?;
+ }
+ };
};
if let Some(time_range) = req.time_range {
@@ -217,6 +255,44 @@ pub async fn search_results(
.switch()?;
}
};
+ if let Some(connector) = filters.connector {
+ if !connector.is_empty() {
+ query_builder
+ .add_filter_clause("connector.keyword".to_string(), connector.clone())
+ .switch()?;
+ }
+ };
+ if let Some(payment_method_type) = filters.payment_method_type {
+ if !payment_method_type.is_empty() {
+ query_builder
+ .add_filter_clause(
+ "payment_method_type.keyword".to_string(),
+ payment_method_type.clone(),
+ )
+ .switch()?;
+ }
+ };
+ if let Some(card_network) = filters.card_network {
+ if !card_network.is_empty() {
+ query_builder
+ .add_filter_clause("card_network.keyword".to_string(), card_network.clone())
+ .switch()?;
+ }
+ };
+ if let Some(card_last_4) = filters.card_last_4 {
+ if !card_last_4.is_empty() {
+ query_builder
+ .add_filter_clause("card_last_4.keyword".to_string(), card_last_4.clone())
+ .switch()?;
+ }
+ };
+ if let Some(payment_id) = filters.payment_id {
+ if !payment_id.is_empty() {
+ query_builder
+ .add_filter_clause("payment_id.keyword".to_string(), payment_id.clone())
+ .switch()?;
+ }
+ };
};
if let Some(time_range) = search_req.time_range {
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index 24dd0effcbb..a33dd100c79 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -9,6 +9,11 @@ pub struct SearchFilters {
pub status: Option<Vec<String>>,
pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>,
pub search_tags: Option<Vec<HashedString<WithType>>>,
+ pub connector: Option<Vec<String>>,
+ pub payment_method_type: Option<Vec<String>>,
+ pub card_network: Option<Vec<String>>,
+ pub card_last_4: Option<Vec<String>>,
+ pub payment_id: Option<Vec<String>>,
}
impl SearchFilters {
pub fn is_all_none(&self) -> bool {
@@ -17,6 +22,11 @@ impl SearchFilters {
&& self.status.is_none()
&& self.customer_email.is_none()
&& self.search_tags.is_none()
+ && self.connector.is_none()
+ && self.payment_method_type.is_none()
+ && self.card_network.is_none()
+ && self.card_last_4.is_none()
+ && self.payment_id.is_none()
}
}
@@ -58,6 +68,10 @@ pub enum SearchIndex {
PaymentIntents,
Refunds,
Disputes,
+ SessionizerPaymentAttempts,
+ SessionizerPaymentIntents,
+ SessionizerRefunds,
+ SessionizerDisputes,
}
#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)]
diff --git a/crates/router/src/consts/opensearch.rs b/crates/router/src/consts/opensearch.rs
index 277b0e946ba..c9eeec1b343 100644
--- a/crates/router/src/consts/opensearch.rs
+++ b/crates/router/src/consts/opensearch.rs
@@ -1,12 +1,16 @@
use api_models::analytics::search::SearchIndex;
-pub const fn get_search_indexes() -> [SearchIndex; 4] {
+pub const fn get_search_indexes() -> [SearchIndex; 8] {
[
SearchIndex::PaymentAttempts,
SearchIndex::PaymentIntents,
SearchIndex::Refunds,
SearchIndex::Disputes,
+ SearchIndex::SessionizerPaymentAttempts,
+ SearchIndex::SessionizerPaymentIntents,
+ SearchIndex::SessionizerRefunds,
+ SearchIndex::SessionizerDisputes,
]
}
-pub const SEARCH_INDEXES: [SearchIndex; 4] = get_search_indexes();
+pub const SEARCH_INDEXES: [SearchIndex; 8] = get_search_indexes();
|
2024-10-17T12:27:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Global search has two components:
- Free flow search, wherein search takes place across all fields available to search upon
- Search on a specific field based on the field filter
In this PR, additional filters have been added for global search to search on a specific field.
A list of values can be provided for every filter field which will be added to the query in order to extract responses from opensearch / elasticsearch.
Existing filters (fields):
- payment_method
- currency
- status
- customer_email
- search_tags
New filters added (fields):
- connector
- payment_method_type
- card_network
- card_last_4
- payment_id
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Enhance search experience on global search using filters
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
The following filters can be used to be searched upon:
- connector
- payment_method_type
- card_network
- card_last_4
- payment_id
Hit the following curl for the `/search` API
```bash
curl --location 'http://localhost:8080/analytics/v1/search' \
--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/126.0.0.0 Safari/537.36' \
--header 'api-key: hyperswitch' \
--header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \
--header 'sec-ch-ua: "Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "macOS"' \
--data '{
"query": "merchant_1726046328",
"filters": {
"payment_method": [
"card"
]
},
"timeRange": {
"startTime": "2024-09-13T00:30:00Z",
"endTime": "2024-10-18T21:45:00Z"
}
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
962afbd084458e9afb11a0278a8210edd9226a3d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6399
|
Bug: chore: address Rust 1.82.0 clippy lints
Address the clippy lints occurring due to new rust version 1.82.0
See https://github.com/juspay/hyperswitch/issues/3391 for more information.
|
diff --git a/add_connector.md b/add_connector.md
index eda368db9c8..4d6e885b7ed 100644
--- a/add_connector.md
+++ b/add_connector.md
@@ -311,7 +311,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
- mandate_reference: None,
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs
index 1454be66c8b..b508596cbc0 100644
--- a/connector-template/transformers.rs
+++ b/connector-template/transformers.rs
@@ -132,8 +132,8 @@ impl<F,T> TryFrom<ResponseRouterData<F, {{project-name | downcase | pascal_case}
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/api_models/src/connector_onboarding.rs b/crates/api_models/src/connector_onboarding.rs
index 2dca57d5953..e86f4a6f2fa 100644
--- a/crates/api_models/src/connector_onboarding.rs
+++ b/crates/api_models/src/connector_onboarding.rs
@@ -42,7 +42,7 @@ pub enum PayPalOnboardingStatus {
MorePermissionsNeeded,
EmailNotVerified,
Success(PayPalOnboardingDone),
- ConnectorIntegrated(admin::MerchantConnectorResponse),
+ ConnectorIntegrated(Box<admin::MerchantConnectorResponse>),
}
#[derive(serde::Serialize, Debug, Clone)]
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index a7be9703d38..237d165d572 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -19,7 +19,7 @@ use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments};
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
pub enum PayoutRequest {
PayoutActionRequest(PayoutActionRequest),
- PayoutCreateRequest(PayoutCreateRequest),
+ PayoutCreateRequest(Box<PayoutCreateRequest>),
PayoutRetrieveRequest(PayoutRetrieveRequest),
}
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index ce9b303066e..56a566d170a 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -229,16 +229,16 @@ pub struct OutgoingWebhook {
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
pub enum OutgoingWebhookContent {
#[schema(value_type = PaymentsResponse, title = "PaymentsResponse")]
- PaymentDetails(payments::PaymentsResponse),
+ PaymentDetails(Box<payments::PaymentsResponse>),
#[schema(value_type = RefundResponse, title = "RefundResponse")]
- RefundDetails(refunds::RefundResponse),
+ RefundDetails(Box<refunds::RefundResponse>),
#[schema(value_type = DisputeResponse, title = "DisputeResponse")]
DisputeDetails(Box<disputes::DisputeResponse>),
#[schema(value_type = MandateResponse, title = "MandateResponse")]
MandateDetails(Box<mandates::MandateResponse>),
#[cfg(feature = "payouts")]
#[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")]
- PayoutDetails(payouts::PayoutCreateResponse),
+ PayoutDetails(Box<payouts::PayoutCreateResponse>),
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index d91e57a2b5d..0bfa1434f69 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -20,8 +20,8 @@ use crate::{
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "db_op", content = "data")]
pub enum DBOperation {
- Insert { insertable: Insertable },
- Update { updatable: Updateable },
+ Insert { insertable: Box<Insertable> },
+ Update { updatable: Box<Updateable> },
}
impl DBOperation {
@@ -33,7 +33,7 @@ impl DBOperation {
}
pub fn table<'a>(&self) -> &'a str {
match self {
- Self::Insert { insertable } => match insertable {
+ Self::Insert { insertable } => match **insertable {
Insertable::PaymentIntent(_) => "payment_intent",
Insertable::PaymentAttempt(_) => "payment_attempt",
Insertable::Refund(_) => "refund",
@@ -45,7 +45,7 @@ impl DBOperation {
Insertable::PaymentMethod(_) => "payment_method",
Insertable::Mandate(_) => "mandate",
},
- Self::Update { updatable } => match updatable {
+ Self::Update { updatable } => match **updatable {
Updateable::PaymentIntentUpdate(_) => "payment_intent",
Updateable::PaymentAttemptUpdate(_) => "payment_attempt",
Updateable::RefundUpdate(_) => "refund",
@@ -83,7 +83,7 @@ pub struct TypedSql {
impl DBOperation {
pub async fn execute(self, conn: &PgPooledConn) -> crate::StorageResult<DBResult> {
Ok(match self {
- Self::Insert { insertable } => match insertable {
+ Self::Insert { insertable } => match *insertable {
Insertable::PaymentIntent(a) => {
DBResult::PaymentIntent(Box::new(a.insert(conn).await?))
}
@@ -107,7 +107,7 @@ impl DBOperation {
}
Insertable::Mandate(m) => DBResult::Mandate(Box::new(m.insert(conn).await?)),
},
- Self::Update { updatable } => match updatable {
+ Self::Update { updatable } => match *updatable {
Updateable::PaymentIntentUpdate(a) => {
DBResult::PaymentIntent(Box::new(a.orig.update(conn, a.update_data).await?))
}
@@ -201,8 +201,8 @@ impl TypedSql {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Insertable {
- PaymentIntent(PaymentIntentNew),
- PaymentAttempt(PaymentAttemptNew),
+ PaymentIntent(Box<PaymentIntentNew>),
+ PaymentAttempt(Box<PaymentAttemptNew>),
Refund(RefundNew),
Address(Box<AddressNew>),
Customer(CustomerNew),
@@ -216,14 +216,14 @@ pub enum Insertable {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "table", content = "data")]
pub enum Updateable {
- PaymentIntentUpdate(PaymentIntentUpdateMems),
- PaymentAttemptUpdate(PaymentAttemptUpdateMems),
+ PaymentIntentUpdate(Box<PaymentIntentUpdateMems>),
+ PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>),
RefundUpdate(RefundUpdateMems),
CustomerUpdate(CustomerUpdateMems),
AddressUpdate(Box<AddressUpdateMems>),
PayoutsUpdate(PayoutsUpdateMems),
PayoutAttemptUpdate(PayoutAttemptUpdateMems),
- PaymentMethodUpdate(PaymentMethodUpdateMems),
+ PaymentMethodUpdate(Box<PaymentMethodUpdateMems>),
MandateUpdate(MandateUpdateMems),
}
diff --git a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
index 4212f7168db..567f519d794 100644
--- a/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
@@ -471,8 +471,8 @@ impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, Pa
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(pg_response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(pg_response.order_number.to_string()),
@@ -491,8 +491,8 @@ impl<F> TryFrom<ResponseRouterData<F, BamboraResponse, PaymentsAuthorizeData, Pa
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(BamboraMeta {
three_d_session_data: response.three_d_session_data.expose(),
@@ -541,8 +541,8 @@ impl<F>
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
@@ -586,8 +586,8 @@ impl<F>
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
@@ -621,8 +621,8 @@ impl<F>
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
@@ -656,8 +656,8 @@ impl<F>
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
diff --git a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
index cc63e1ad7cc..798f28d1f0a 100644
--- a/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
@@ -284,8 +284,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BillwerkPaymentsResponse, T, PaymentsRe
};
let payments_response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.handle.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.handle),
diff --git a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
index 1c42bfd08c8..333398dfa90 100644
--- a/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
@@ -159,8 +159,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, BitpayPaymentsResponse, T, PaymentsResp
status: enums::AttemptStatus::from(attempt_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
diff --git a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
index 49493127621..2a282414f4b 100644
--- a/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs
@@ -269,8 +269,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.data.attempt_id.clone(),
),
- redirection_data: Some(redirection_data),
- mandate_reference: None,
+ redirection_data: Box::new(Some(redirection_data)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -302,8 +302,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, Paym
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,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
index 3633c366c4c..41a5306527c 100644
--- a/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
@@ -146,8 +146,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsRe
let response_data = timeline.context.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id.clone(),
- redirection_data: Some(redirection_data),
- mandate_reference: None,
+ redirection_data: Box::new(Some(redirection_data)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.id.clone()),
diff --git a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
index 4440346db6b..1228edcaaea 100644
--- a/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs
@@ -183,8 +183,8 @@ impl<F, T>
.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,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
index e4b011f6204..ccecdaa3d41 100644
--- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
@@ -298,16 +298,16 @@ impl
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
- redirection_data: Some(RedirectForm::Form {
+ redirection_data: Box::new(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.clone()),
("signed_on".to_string(), signed_on.clone()),
]),
- }),
+ })),
mandate_reference: if item.data.request.is_mandate_payment() {
- Some(MandateReference {
+ Box::new(Some(MandateReference {
connector_mandate_id: item.response.mandate_id,
payment_method_id: None,
mandate_metadata: Some(serde_json::json!(DeutschebankMandateMetadata {
@@ -325,9 +325,9 @@ impl
reference: Secret::from(reference.clone()),
signed_on,
})),
- })
+ }))
} else {
- None
+ Box::new(None)
},
connector_metadata: None,
network_txn_id: None,
@@ -375,8 +375,8 @@ impl
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -578,8 +578,8 @@ impl
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -637,8 +637,8 @@ impl
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
index 722c78442da..856736842f9 100644
--- a/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
@@ -124,8 +124,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DigitalvirgoPaymentsResponse, T, Paymen
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
index d21fa481579..f2a6e1b6a6f 100644
--- a/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs
@@ -326,8 +326,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResp
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
@@ -360,8 +360,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, Payments
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
@@ -391,8 +391,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, Payme
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
@@ -420,8 +420,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, Paymen
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
index cdcd82f5b4f..6f4f303ae8e 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
@@ -374,8 +374,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservPaymentsResponse, T, PaymentsResp
resource_id: ResponseId::ConnectorTransactionId(
gateway_resp.transaction_processing_details.transaction_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -413,8 +413,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservSyncResponse, T, PaymentsResponse
.transaction_id
.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
index 7f88903e867..a5362283e7a 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
@@ -361,8 +361,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FiservemeaPaymentsResponse, T, Payments
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.ipg_transaction_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id,
diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
index a401af51008..3d11c24688d 100644
--- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
@@ -604,8 +604,8 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.txn_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: get_qr_metadata(response)?,
network_txn_id: None,
connector_response_reference_id: None,
@@ -640,8 +640,8 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.txn_id),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -684,8 +684,8 @@ impl<F>
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.txn_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -924,8 +924,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: item.data.request.connector_transaction_id.clone(),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -963,8 +963,8 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: item.data.request.connector_transaction_id.clone(),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1130,8 +1130,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tran_id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1241,8 +1241,8 @@ impl TryFrom<PaymentsCancelResponseRouterData<FiuuPaymentCancelResponse>>
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.tran_id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
index d04ea7bfee4..6e67409238d 100644
--- a/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
@@ -299,8 +299,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsResponse, T, PaymentsRespo
status: get_status(response_code, action),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
@@ -342,8 +342,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, FortePaymentsSyncResponse, T, PaymentsR
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
@@ -411,8 +411,8 @@ impl TryFrom<PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
@@ -479,8 +479,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ForteCancelResponse, T, PaymentsRespons
status: enums::AttemptStatus::from(item.response.response.response_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(transaction_id.to_string()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(ForteMeta {
auth_id: item.response.authorization_code,
})),
diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
index 2e3919cfc48..66525d49c63 100644
--- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs
@@ -213,8 +213,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobepayPaymentsResponse, T, PaymentsRe
.order_id
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
@@ -287,8 +287,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, GlobepaySyncResponse, T, PaymentsRespon
status: enums::AttemptStatus::from(globepay_status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(globepay_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
index a01e2cf918d..427fef3836c 100644
--- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs
@@ -379,8 +379,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
@@ -430,8 +430,8 @@ impl<F>
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
@@ -479,8 +479,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
@@ -559,8 +559,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
@@ -616,8 +616,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.to_string(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
index dc5f64bee18..cef3d684e7b 100644
--- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs
@@ -507,8 +507,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, MolliePaymentsResponse, T, PaymentsResp
status: enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: url,
- mandate_reference: None,
+ redirection_data: Box::new(url),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
index eeb24233bef..4761581401f 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
@@ -365,8 +365,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPreAuthOrDebitResponse, T, Paym
status: get_status(transaction.status.clone(), item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id),
@@ -445,8 +445,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, NexinetsPaymentResponse, T, PaymentsRes
status: get_status(item.response.status, item.response.transaction_type),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order.order_id),
diff --git a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
index 1677343fe38..d593864dbfc 100644
--- a/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
@@ -353,8 +353,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id),
@@ -626,8 +626,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
- redirection_data: Some(redirection_form.clone()),
- mandate_reference: None,
+ redirection_data: Box::new(Some(redirection_form.clone())),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id),
@@ -744,8 +744,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.response.operation.order_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.operation.order_id),
@@ -867,8 +867,8 @@ impl<F>
status: AttemptStatus::from(item.response.operation_result),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: item.data.request.connector_meta.clone(),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
@@ -923,8 +923,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -986,8 +986,8 @@ impl<F>
resource_id: ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
index ab209a4db05..1f16a14fde3 100644
--- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
@@ -594,14 +594,14 @@ impl<F, T> TryFrom<ResponseRouterData<F, NovalnetPaymentsResponse, T, PaymentsRe
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
- redirection_data,
- mandate_reference: mandate_reference_id.as_ref().map(|id| {
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| {
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
mandate_metadata: None,
}
- }),
+ })),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
@@ -995,14 +995,14 @@ impl<F>
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
- redirection_data: None,
- mandate_reference: mandate_reference_id.as_ref().map(|id| {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference_id.as_ref().map(|id| {
MandateReference {
connector_mandate_id: Some(id.clone()),
payment_method_id: None,
mandate_metadata: None,
}
- }),
+ })),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
@@ -1085,8 +1085,8 @@ impl<F>
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
@@ -1254,8 +1254,8 @@ impl<F>
.clone()
.map(ResponseId::ConnectorTransactionId)
.unwrap_or(ResponseId::NoResponseId),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: transaction_id.clone(),
diff --git a/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
index 47c5c40363e..af29d54117a 100644
--- a/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
@@ -432,8 +432,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayeezyPaymentsResponse, T, PaymentsRes
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
index 7b3792c0e24..0b2b7030528 100644
--- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs
@@ -210,8 +210,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsResponse, T, PaymentsRespon
status: enums::AttemptStatus::from(item.response.status.status_code),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -260,8 +260,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCaptureResponse, T, Payment
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -335,8 +335,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsCancelResponse, T, Payments
status: enums::AttemptStatus::from(item.response.status.status_code.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -464,8 +464,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsRe
status: enums::AttemptStatus::from(order.status.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.order_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: order
diff --git a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
index 770688a3468..93ba3425978 100644
--- a/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
@@ -336,8 +336,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResp
let response = error_response.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(connector_transaction_id),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_identifier),
diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
index b2151c524be..0e6d3128b30 100644
--- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs
@@ -385,8 +385,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResp
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.payment.reference_id,
diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
index 0f112566796..a8e9a7ad829 100644
--- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
@@ -372,8 +372,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsRespon
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
index c0ee0fdae94..ca18179ff17 100644
--- a/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/thunes/transformers.rs
@@ -129,8 +129,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, ThunesPaymentsResponse, T, PaymentsResp
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
index e97cf228729..fc485e65727 100644
--- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
@@ -226,8 +226,8 @@ fn get_error_response(
fn get_payments_response(connector_response: TsysResponse) -> PaymentsResponseData {
PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(connector_response.transaction_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_response.transaction_id),
@@ -246,8 +246,8 @@ fn get_payments_sync_response(
.transaction_id
.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
index e04eae63b4c..b13d029185f 100644
--- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
@@ -277,8 +277,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponse, T, PaymentsRespon
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
@@ -351,8 +351,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe
resource_id: ResponseId::ConnectorTransactionId(
payment_response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment_response
@@ -392,8 +392,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, VoltPaymentsResponseData, T, PaymentsRe
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: webhook_response
diff --git a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
index 09ffac81425..05986631c67 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
@@ -570,8 +570,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, Payment, T, PaymentsResponseData>>
status: get_status((item.response.status, item.response.capture_method)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
@@ -621,8 +621,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, PaymentResponse, T, PaymentsResponseDat
)),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment.id),
diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
index a564fb4ee60..d4a18a15182 100644
--- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
@@ -939,8 +939,8 @@ fn get_zen_response(
};
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -983,8 +983,8 @@ impl<F, T> TryFrom<ResponseRouterData<F, CheckoutResponse, T, PaymentsResponseDa
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index af901a80558..9f079f1312e 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -275,7 +275,7 @@ pub enum CustomerUpdate {
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
- connector_customer: Option<pii::SecretSerdeValue>,
+ connector_customer: Box<Option<pii::SecretSerdeValue>>,
default_billing_address: Option<Encryption>,
default_shipping_address: Option<Encryption>,
default_payment_method_id: Option<Option<String>>,
@@ -312,7 +312,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
description,
phone_country_code,
metadata,
- connector_customer,
+ connector_customer: *connector_customer,
modified_at: date_time::now(),
default_billing_address,
default_shipping_address,
@@ -366,7 +366,7 @@ pub enum CustomerUpdate {
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
- connector_customer: Option<pii::SecretSerdeValue>,
+ connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
},
ConnectorCustomer {
@@ -397,7 +397,7 @@ impl From<CustomerUpdate> for CustomerUpdateInternal {
description,
phone_country_code,
metadata,
- connector_customer,
+ connector_customer: *connector_customer,
modified_at: date_time::now(),
address_id,
default_payment_method_id: None,
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 66b98389818..9418f6f8f1e 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -88,20 +88,20 @@ pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
connector_name: Option<String>,
- connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
test_mode: Option<bool>,
disabled: Option<bool>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
- connector_webhook_details: Option<pii::SecretSerdeValue>,
+ connector_webhook_details: Box<Option<pii::SecretSerdeValue>>,
applepay_verified_domains: Option<Vec<String>>,
- pm_auth_config: Option<pii::SecretSerdeValue>,
+ pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
- connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
- additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+ connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
+ additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
@@ -113,18 +113,18 @@ pub enum MerchantConnectorAccountUpdate {
pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
- connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>,
+ connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
disabled: Option<bool>,
payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
connector_webhook_details: Option<pii::SecretSerdeValue>,
applepay_verified_domains: Option<Vec<String>>,
- pm_auth_config: Option<pii::SecretSerdeValue>,
+ pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
- connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
- additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+ connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
+ additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
@@ -413,9 +413,9 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
frm_configs: None,
frm_config: frm_configs,
modified_at: Some(date_time::now()),
- connector_webhook_details,
+ connector_webhook_details: *connector_webhook_details,
applepay_verified_domains,
- pm_auth_config,
+ pm_auth_config: *pm_auth_config,
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
@@ -475,7 +475,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
modified_at: Some(date_time::now()),
connector_webhook_details,
applepay_verified_domains,
- pm_auth_config,
+ pm_auth_config: *pm_auth_config,
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index 6682ac1ad44..2ed77c8072d 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -17,8 +17,8 @@ pub struct RefundsResponseData {
pub enum PaymentsResponseData {
TransactionResponse {
resource_id: ResponseId,
- redirection_data: Option<RedirectForm>,
- mandate_reference: Option<MandateReference>,
+ redirection_data: Box<Option<RedirectForm>>,
+ mandate_reference: Box<Option<MandateReference>>,
connector_metadata: Option<serde_json::Value>,
network_txn_id: Option<String>,
connector_response_reference_id: Option<String>,
diff --git a/crates/router/src/compatibility/stripe/webhooks.rs b/crates/router/src/compatibility/stripe/webhooks.rs
index 8445011f569..ddc291e6b13 100644
--- a/crates/router/src/compatibility/stripe/webhooks.rs
+++ b/crates/router/src/compatibility/stripe/webhooks.rs
@@ -81,7 +81,7 @@ impl OutgoingWebhookType for StripeOutgoingWebhook {
#[derive(Serialize, Debug)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
pub enum StripeWebhookObject {
- PaymentIntent(StripePaymentIntentResponse),
+ PaymentIntent(Box<StripePaymentIntentResponse>),
Refund(StripeRefundResponse),
Dispute(StripeDisputeResponse),
Mandate(StripeMandateResponse),
@@ -327,9 +327,9 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject {
fn from(value: api::OutgoingWebhookContent) -> Self {
match value {
api::OutgoingWebhookContent::PaymentDetails(payment) => {
- Self::PaymentIntent(payment.into())
+ Self::PaymentIntent(Box::new((*payment).into()))
}
- api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund(refund.into()),
+ api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()),
api::OutgoingWebhookContent::DisputeDetails(dispute) => {
Self::Dispute((*dispute).into())
}
@@ -337,7 +337,7 @@ impl From<api::OutgoingWebhookContent> for StripeWebhookObject {
Self::Mandate((*mandate).into())
}
#[cfg(feature = "payouts")]
- api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout(payout.into()),
+ api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()),
}
}
}
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 5e803b593ee..7355617b53a 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -763,8 +763,8 @@ impl<F, T>
},
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index ca13e57e401..21c9c34409a 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3273,8 +3273,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment_psp_reference,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.reference),
@@ -3308,8 +3308,8 @@ impl<F>
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -3374,8 +3374,8 @@ pub fn get_adyen_response(
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(response.psp_reference),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id,
connector_response_reference_id: Some(response.merchant_reference),
@@ -3438,8 +3438,8 @@ pub fn get_webhook_response(
.payment_reference
.unwrap_or(response.transaction_id),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.merchant_reference_id),
@@ -3508,8 +3508,8 @@ pub fn get_redirection_response(
Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()),
None => types::ResponseId::NoResponseId,
},
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: response
@@ -3566,8 +3566,8 @@ pub fn get_present_to_shopper_response(
Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()),
None => types::ResponseId::NoResponseId,
},
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: response
@@ -3623,8 +3623,8 @@ pub fn get_qr_code_response(
Some(psp) => types::ResponseId::ConnectorTransactionId(psp.to_string()),
None => types::ResponseId::NoResponseId,
},
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: response
@@ -3666,8 +3666,8 @@ pub fn get_redirection_error_response(
// We don't get connector transaction id for redirections in Adyen.
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response
@@ -4036,8 +4036,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
status: storage_enums::AttemptStatus::Pending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(connector_transaction_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.reference),
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index d3824e9d0da..ad7ae2716f1 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -570,8 +570,8 @@ impl<F, T>
reference_id: Some(item.response.id.clone()),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
@@ -613,8 +613,8 @@ impl
reference_id: Some(item.response.id.clone()),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 903470ae952..6961a87326b 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -388,20 +388,19 @@ impl<F, T>
status: enums::AttemptStatus::Charged,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: item.response.customer_profile_id.map(
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(item.response.customer_profile_id.map(
|customer_profile_id| types::MandateReference {
- connector_mandate_id: item
- .response
- .customer_payment_profile_id_list
- .first()
- .map(|payment_profile_id| {
- format!("{customer_profile_id}-{payment_profile_id}")
- }),
+ connector_mandate_id:
+ item.response.customer_payment_profile_id_list.first().map(
+ |payment_profile_id| {
+ format!("{customer_profile_id}-{payment_profile_id}")
+ },
+ ),
payment_method_id: None,
mandate_metadata: None,
},
- ),
+ )),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1125,8 +1124,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
@@ -1198,8 +1197,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
@@ -1528,8 +1527,8 @@ impl<F, Req>
resource_id: types::ResponseId::ConnectorTransactionId(
transaction.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
diff --git a/crates/router/src/connector/bamboraapac/transformers.rs b/crates/router/src/connector/bamboraapac/transformers.rs
index 819c918338e..8fcbcd98f09 100644
--- a/crates/router/src/connector/bamboraapac/transformers.rs
+++ b/crates/router/src/connector/bamboraapac/transformers.rs
@@ -39,14 +39,14 @@ pub fn get_payment_body(
let transaction_data = get_transaction_body(req)?;
let body = format!(
r#"
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSinglePayment>
<dts:trnXML>
<![CDATA[
{}
- ]]>
+ ]]>
</dts:trnXML>
</dts:SubmitSinglePayment>
</soapenv:Body>
@@ -293,8 +293,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
@@ -354,12 +354,12 @@ pub fn get_setup_mandate_body(req: &types::SetupMandateRouterData) -> Result<Vec
<sipp:tokeniseCreditCardXML>
<![CDATA[
<TokeniseCreditCard>
- <CardNumber>{}</CardNumber>
+ <CardNumber>{}</CardNumber>
<ExpM>{}</ExpM>
<ExpY>{}</ExpY>
<CardHolderName>{}</CardHolderName>
<TokeniseAlgorithmID>2</TokeniseAlgorithmID>
- <UserName>{}</UserName>
+ <UserName>{}</UserName>
<Password>{}</Password>
</TokeniseCreditCard>
]]>
@@ -460,12 +460,12 @@ impl<F>
status: enums::AttemptStatus::Charged,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: Some(types::MandateReference {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(Some(types::MandateReference {
connector_mandate_id: Some(connector_mandate_id),
payment_method_id: None,
mandate_metadata: None,
- }),
+ })),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -501,7 +501,7 @@ pub fn get_capture_body(
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Body>
<dts:SubmitSingleCapture>
@@ -514,8 +514,8 @@ pub fn get_capture_body(
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
- </Capture>
- ]]>
+ </Capture>
+ ]]>
</dts:trnXML>
</dts:SubmitSingleCapture>
</soapenv:Body>
@@ -610,8 +610,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
@@ -663,7 +663,7 @@ pub fn get_refund_body(
let auth_details = BamboraapacAuthType::try_from(&req.router_data.connector_auth_type)?;
let body = format!(
r#"
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
@@ -677,9 +677,9 @@ pub fn get_refund_body(
<Security>
<UserName>{}</UserName>
<Password>{}</Password>
- </Security>
+ </Security>
</Refund>
- ]]>
+ ]]>
</dts:trnXML>
</dts:SubmitSingleRefund>
</soapenv:Body>
@@ -792,7 +792,7 @@ pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let body = format!(
r#"
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
@@ -810,8 +810,8 @@ pub fn get_payment_sync_body(req: &types::PaymentsSyncRouterData) -> Result<Vec<
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
- </QueryTransaction>
- ]]>
+ </QueryTransaction>
+ ]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
@@ -909,8 +909,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
connector_transaction_id.to_owned(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(connector_transaction_id),
@@ -961,7 +961,7 @@ pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>
let body = format!(
r#"
- <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:dts="http://www.ippayments.com.au/interface/api/dts">
<soapenv:Header/>
<soapenv:Body>
@@ -979,8 +979,8 @@ pub fn get_refund_sync_body(req: &types::RefundSyncRouterData) -> Result<Vec<u8>
<UserName>{}</UserName>
<Password>{}</Password>
</Security>
- </QueryTransaction>
- ]]>
+ </QueryTransaction>
+ ]]>
</dts:queryXML>
</dts:QueryTransaction>
</soapenv:Body>
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index ad75328322d..b5669decd86 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -412,8 +412,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
info_response.id.clone(),
),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -1516,8 +1516,8 @@ fn get_payment_response(
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -1829,8 +1829,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -1852,8 +1852,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
index e6f01700c6d..468f68dc340 100644
--- a/crates/router/src/connector/bluesnap.rs
+++ b/crates/router/src/connector/bluesnap.rs
@@ -741,10 +741,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(services::RedirectForm::BlueSnap {
+ redirection_data: Box::new(Some(services::RedirectForm::BlueSnap {
payment_fields_token,
- }),
- mandate_reference: None,
+ })),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 39be2517e4b..6db0ddac49b 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -875,8 +875,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index bc9eb4e3722..777b795a438 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -301,8 +301,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, BokuResponse, T, types::Payments
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_id),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index b7515a964bb..948d6f2cfd3 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -439,14 +439,14 @@ impl<F>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
+ |pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
- }
- }),
+ },
+ )),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -464,12 +464,12 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
+ redirection_data: Box::new(Some(get_braintree_redirect_form(
*client_token_data,
item.data.get_payment_method_token()?,
item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
+ )?)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -614,14 +614,14 @@ impl<F>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
+ |pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
- }
- }),
+ },
+ )),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -639,12 +639,12 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
+ redirection_data: Box::new(Some(get_braintree_redirect_form(
*client_token_data,
item.data.get_payment_method_token()?,
item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
+ )?)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -696,14 +696,14 @@ impl<F>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
+ |pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
- }
- }),
+ },
+ )),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -760,14 +760,14 @@ impl<F>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(transaction_data.payment_method.as_ref().map(
+ |pm| MandateReference {
connector_mandate_id: Some(pm.id.clone().expose()),
payment_method_id: None,
mandate_metadata: None,
- }
- }),
+ },
+ )),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1274,8 +1274,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1384,8 +1384,8 @@ impl<F, T>
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1489,8 +1489,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
edge_data.node.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index 3e951b3ac86..686a9d57ac3 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -688,8 +688,8 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
};
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
@@ -741,8 +741,8 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>>
};
let payments_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -819,8 +819,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>>
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(response.action_id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -920,8 +920,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(resource_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: item.response.reference,
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index da768258614..4331b4d7983 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -2559,8 +2559,8 @@ fn get_payment_response(
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: info_response.processor_information.as_ref().and_then(
|processor_information| processor_information.network_transaction_id.clone(),
@@ -2647,18 +2647,20 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(services::RedirectForm::CybersourceAuthSetup {
- access_token: info_response
- .consumer_authentication_information
- .access_token,
- ddc_url: info_response
- .consumer_authentication_information
- .device_data_collection_url,
- reference_id: info_response
- .consumer_authentication_information
- .reference_id,
- }),
- mandate_reference: None,
+ redirection_data: Box::new(Some(
+ services::RedirectForm::CybersourceAuthSetup {
+ access_token: info_response
+ .consumer_authentication_information
+ .access_token,
+ ddc_url: info_response
+ .consumer_authentication_information
+ .device_data_collection_url,
+ reference_id: info_response
+ .consumer_authentication_information
+ .reference_id,
+ },
+ )),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
@@ -3066,8 +3068,8 @@ impl<F>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!({
"three_ds_data": three_ds_data
})),
@@ -3311,8 +3313,8 @@ impl
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.processor_information.as_ref().and_then(
|processor_information| {
@@ -3449,8 +3451,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -3471,8 +3473,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs
index b28504a1d83..e9dcfd87071 100644
--- a/crates/router/src/connector/datatrans/transformers.rs
+++ b/crates/router/src/connector/datatrans/transformers.rs
@@ -293,8 +293,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
response.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -411,8 +411,8 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<DatatransSyncResponse>>
status: enums::AttemptStatus::from(response),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs
index 2cf5960bf75..79caa3d0a76 100644
--- a/crates/router/src/connector/dummyconnector/transformers.rs
+++ b/crates/router/src/connector/dummyconnector/transformers.rs
@@ -253,8 +253,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::Paym
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 19568ae4671..d17c8a8fdfd 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -274,8 +274,8 @@ fn get_payment_response(
}),
_ => Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(response.id),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.reference,
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index c0360a94a51..dac90b28366 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -523,8 +523,8 @@ impl<F>
connector_response_reference_id: None,
incremental_authorization_allowed: None,
resource_id: ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
network_txn_id: None,
charge_id: None,
}),
@@ -674,8 +674,8 @@ impl<F>
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
- redirection_data: None,
- mandate_reference: Some(mandate_reference),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(Some(mandate_reference)),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -710,8 +710,8 @@ impl<F>
status: enums::AttemptStatus::from(item.response.payments.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.payments.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index de92168036c..ec94b322fe7 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -382,8 +382,8 @@ fn get_iatpay_response(
types::PaymentsResponseData::TransactionResponse {
resource_id: id,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
@@ -393,8 +393,8 @@ fn get_iatpay_response(
}
None => types::PaymentsResponseData::TransactionResponse {
resource_id: id.clone(),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs
index 41c41408381..15dfb1ce240 100644
--- a/crates/router/src/connector/itaubank/transformers.rs
+++ b/crates/router/src/connector/itaubank/transformers.rs
@@ -280,8 +280,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.txid.to_owned(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
@@ -368,8 +368,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.txid.to_owned(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index e6f0bab9c2c..ea83e20d99d 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -272,8 +272,8 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.order_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
@@ -394,8 +394,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.order_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -474,8 +474,8 @@ impl<F>
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(resource_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 03c63d66795..6ff52bb7eb1 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -259,10 +259,10 @@ impl<F, T>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(trace_id.clone()),
- redirection_data: Some(services::RedirectForm::Mifinity {
+ redirection_data: Box::new(Some(services::RedirectForm::Mifinity {
initialization_token,
- }),
- mandate_reference: None,
+ })),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(trace_id),
@@ -276,8 +276,8 @@ impl<F, T>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -345,8 +345,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
transaction_reference,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -360,8 +360,8 @@ impl<F, T>
status: enums::AttemptStatus::from(status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -376,8 +376,8 @@ impl<F, T>
status: item.data.status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 9db1cb3701a..2831b63fcbe 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -930,7 +930,7 @@ pub struct MultisafepayPaymentsResponse {
#[serde(untagged)]
pub enum MultisafepayAuthResponse {
ErrorResponse(MultisafepayErrorResponse),
- PaymentResponse(MultisafepayPaymentsResponse),
+ PaymentResponse(Box<MultisafepayPaymentsResponse>),
}
impl<F, T>
@@ -979,16 +979,18 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
payment_response.data.order_id.clone(),
),
- redirection_data,
- mandate_reference: payment_response
- .data
- .payment_details
- .and_then(|payment_details| payment_details.recurring_id)
- .map(|id| types::MandateReference {
- connector_mandate_id: Some(id.expose()),
- payment_method_id: None,
- mandate_metadata: None,
- }),
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(
+ payment_response
+ .data
+ .payment_details
+ .and_then(|payment_details| payment_details.recurring_id)
+ .map(|id| types::MandateReference {
+ connector_mandate_id: Some(id.expose()),
+ payment_method_id: None,
+ mandate_metadata: None,
+ }),
+ ),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index af2a9fe56bb..0ec9cc94888 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -185,7 +185,7 @@ impl
Response::Approved => (
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(services::RedirectForm::Nmi {
+ redirection_data: Box::new(Some(services::RedirectForm::Nmi {
amount: utils::to_currency_base_unit_asf64(
amount_data,
currency_data.to_owned(),
@@ -206,8 +206,8 @@ impl
},
)?,
order_id: item.data.connector_request_reference_id.clone(),
- }),
- mandate_reference: None,
+ })),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transactionid),
@@ -360,8 +360,8 @@ impl
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
@@ -743,8 +743,8 @@ impl
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.to_owned(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
@@ -838,8 +838,8 @@ impl<T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
@@ -895,8 +895,8 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
@@ -946,8 +946,8 @@ impl<T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transactionid.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
@@ -997,8 +997,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::Payments
status: enums::AttemptStatus::from(NmiStatus::from(trn.condition)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(trn.transaction_id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index 5c3de332b70..634a9feccf3 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -596,8 +596,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
order.id.to_string(),
),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id,
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index d1d7122f49e..68c25f58acb 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1598,15 +1598,17 @@ where
.map_or(response.order_id.clone(), Some) // For paypal there will be no transaction_id, only order_id will be present
.map(types::ResponseId::ConnectorTransactionId)
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
- redirection_data,
- mandate_reference: response
- .payment_option
- .and_then(|po| po.user_payment_option_id)
- .map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
- payment_method_id: None,
- mandate_metadata: None,
- }),
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(
+ response
+ .payment_option
+ .and_then(|po| po.user_payment_option_id)
+ .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 {
Some(
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index 44069f3650b..44445a3d7d9 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -144,8 +144,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index 8f1579ac1ff..1e8239d377b 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -138,8 +138,8 @@ impl<F, T>
let response_data = if attempt_status != OpennodePaymentStatus::Underpaid {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
- redirection_data: Some(redirection_data),
- mandate_reference: None,
+ redirection_data: Box::new(Some(redirection_data)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.data.order_id,
diff --git a/crates/router/src/connector/paybox/transformers.rs b/crates/router/src/connector/paybox/transformers.rs
index d02f75693c4..b52a6e463f6 100644
--- a/crates/router/src/connector/paybox/transformers.rs
+++ b/crates/router/src/connector/paybox/transformers.rs
@@ -597,8 +597,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
@@ -657,8 +657,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
@@ -686,10 +686,10 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(RedirectForm::Html {
+ redirection_data: Box::new(Some(RedirectForm::Html {
html_data: data.peek().to_string(),
- }),
- mandate_reference: None,
+ })),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -731,8 +731,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PayboxSyncResponse, T, types::Pa
resource_id: types::ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
@@ -916,8 +916,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
response.paybox_order_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PayboxMeta {
connector_request_id: response.transaction_number.clone()
})),
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 4eac0a6f94d..ceeafb50251 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -246,12 +246,14 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData {
};
Ok(Self::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),
- redirection_data,
- mandate_reference: value.buyer_key.clone().map(|buyer_key| MandateReference {
- connector_mandate_id: Some(buyer_key.expose()),
- payment_method_id: None,
- mandate_metadata: None,
- }),
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(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,
connector_response_reference_id: None,
@@ -316,9 +318,9 @@ impl From<&SaleQuery> for types::PaymentsResponseData {
fn from(value: &SaleQuery) -> Self {
Self::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),
- redirection_data: None,
+ redirection_data: Box::new(None),
// mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct
- mandate_reference: None,
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -536,8 +538,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payme_sale_id.to_owned(),
),
- redirection_data: Some(services::RedirectForm::Payme),
- mandate_reference: None,
+ redirection_data: Box::new(Some(services::RedirectForm::Payme)),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1110,8 +1112,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>>
// Since we are not receiving payme_sale_id, we are not populating the transaction response
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index 274aab8e504..7b866971b01 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -1117,14 +1117,14 @@ impl
status: storage_enums::AttemptStatus::AuthenticationSuccessful,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
- charge_id: None,
- }),
+ charge_id: None,
+ }),
..data.clone()
})
}
@@ -1168,8 +1168,8 @@ impl
status: storage_enums::AttemptStatus::AuthenticationSuccessful,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 30aaf5a84a8..e30a3f07c9b 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1388,8 +1388,8 @@ impl<F, T>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: order_id,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: purchase_units
@@ -1511,11 +1511,11 @@ impl<F, T>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: Some(services::RedirectForm::from((
+ redirection_data: Box::new(Some(services::RedirectForm::from((
link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
services::Method::Get,
- ))),
- mandate_reference: None,
+ )))),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
@@ -1566,11 +1566,11 @@ impl
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: Some(services::RedirectForm::from((
+ redirection_data: Box::new(Some(services::RedirectForm::from((
link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
services::Method::Get,
- ))),
- mandate_reference: None,
+ )))),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: Some(
@@ -1624,8 +1624,8 @@ impl
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
@@ -1662,8 +1662,8 @@ impl<F>
status: storage_enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -1712,11 +1712,11 @@ impl<F>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: Some(paypal_threeds_link((
+ redirection_data: Box::new(Some(paypal_threeds_link((
link,
item.data.request.complete_authorize_url.clone(),
- ))?),
- mandate_reference: None,
+ ))?)),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
network_txn_id: None,
connector_response_reference_id: None,
@@ -1780,8 +1780,8 @@ impl<F, T>
.order_id
.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -2115,8 +2115,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
resource_id: types::ResponseId::ConnectorTransactionId(
item.data.request.connector_transaction_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(serde_json::json!(PaypalMeta {
authorize_id: connector_payment_id.authorize_id,
capture_id: Some(item.response.id.clone()),
@@ -2173,8 +2173,8 @@ impl<F, T>
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index 32d651787b6..2d1ce4771ca 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -263,8 +263,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.internal_reference.to_string(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: item
.response
.authorization
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs
index f0cf91b9cf6..29d4db1297f 100644
--- a/crates/router/src/connector/plaid/transformers.rs
+++ b/crates/router/src/connector/plaid/transformers.rs
@@ -308,8 +308,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
@@ -394,8 +394,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::Pay
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.payment_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment_id),
diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs
index 6862c7c4c80..24bd4642c01 100644
--- a/crates/router/src/connector/prophetpay/transformers.rs
+++ b/crates/router/src/connector/prophetpay/transformers.rs
@@ -201,8 +201,8 @@ impl<F>
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -401,8 +401,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transaction_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
@@ -452,8 +452,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transaction_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -503,8 +503,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.transaction_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 044a64b413c..bcd0693500a 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -474,8 +474,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
data.id.to_owned(),
), //transaction_id is also the field but this id is used to initiate a refund
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/razorpay/transformers.rs b/crates/router/src/connector/razorpay/transformers.rs
index fde72cac100..6755a2d1816 100644
--- a/crates/router/src/connector/razorpay/transformers.rs
+++ b/crates/router/src/connector/razorpay/transformers.rs
@@ -789,8 +789,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
second_factor.epg_txn_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(second_factor.txn_id),
@@ -1010,8 +1010,8 @@ impl<F, T>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.second_factor.epg_txn_id,
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.second_factor.txn_id),
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 3b768151115..570d3b90aff 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -759,8 +759,8 @@ impl TryFrom<types::PaymentsPreprocessingResponseRouterData<Shift4ThreeDsRespons
},
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(Shift4CardToken {
id: item.response.token.id,
@@ -802,13 +802,14 @@ impl<T, F>
)),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
- redirection_data: item
- .response
- .flow
- .and_then(|flow| flow.redirect)
- .and_then(|redirect| redirect.redirect_url)
- .map(|url| services::RedirectForm::from((url, services::Method::Get))),
- mandate_reference: None,
+ redirection_data: Box::new(
+ item.response
+ .flow
+ .and_then(|flow| flow.redirect)
+ .and_then(|redirect| redirect.redirect_url)
+ .map(|url| services::RedirectForm::from((url, services::Method::Get))),
+ ),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 63720696ef4..fe69f43777e 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2490,8 +2490,8 @@ impl<F, T>
});
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata,
network_txn_id,
connector_response_reference_id: Some(item.response.id),
@@ -2697,8 +2697,8 @@ impl<F, T>
});
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
@@ -2776,8 +2776,8 @@ impl<F, T>
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data,
- mandate_reference,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id),
@@ -3270,7 +3270,7 @@ pub struct MitExemption {
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum LatestAttempt {
- PaymentIntentAttempt(LatestPaymentAttempt),
+ PaymentIntentAttempt(Box<LatestPaymentAttempt>),
SetupAttempt(String),
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
@@ -3480,8 +3480,8 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme
} else {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.id.clone()),
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index fbff19fd0ad..3b109a7f02e 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -727,8 +727,8 @@ fn handle_cards_response(
};
let payment_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(response.instance_id.clone()),
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -754,11 +754,11 @@ fn handle_bank_redirects_response(
resource_id: types::ResponseId::ConnectorTransactionId(
response.payment_request_id.to_string(),
),
- redirection_data: Some(services::RedirectForm::from((
+ redirection_data: Box::new(Some(services::RedirectForm::from((
response.gateway_url,
services::Method::Get,
- ))),
- mandate_reference: None,
+ )))),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -791,8 +791,8 @@ fn handle_bank_redirects_error_response(
});
let payment_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -852,8 +852,8 @@ fn handle_bank_redirects_sync_response(
.payment_request_id
.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -900,8 +900,8 @@ pub fn handle_webhook_response(
};
let payment_response_data = types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs
index 999b81a2ff9..4dd455d0da3 100644
--- a/crates/router/src/connector/wellsfargo/transformers.rs
+++ b/crates/router/src/connector/wellsfargo/transformers.rs
@@ -1791,8 +1791,8 @@ fn get_payment_response(
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: info_response.processor_information.as_ref().and_then(
|processor_information| processor_information.network_transaction_id.clone(),
@@ -2003,8 +2003,8 @@ impl
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
network_txn_id: item.response.processor_information.as_ref().and_then(
|processor_information| {
@@ -2141,8 +2141,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
@@ -2163,8 +2163,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
diff --git a/crates/router/src/connector/wellsfargopayout/transformers.rs b/crates/router/src/connector/wellsfargopayout/transformers.rs
index e335c3cf59a..135cb5f53cb 100644
--- a/crates/router/src/connector/wellsfargopayout/transformers.rs
+++ b/crates/router/src/connector/wellsfargopayout/transformers.rs
@@ -134,8 +134,8 @@ impl<F, T>
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 777594a4534..79147a35b5e 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -260,8 +260,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
response,
Some(data.request.connector_transaction_id.clone()),
))?,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
@@ -403,8 +403,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: data.request.connector_transaction_id.clone(),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
@@ -506,8 +506,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
response,
Some(data.request.connector_transaction_id.clone()),
))?,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id,
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index fee004a6e4c..efdd0fa6878 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -485,8 +485,8 @@ impl<F, T>
router_data.response,
optional_correlation_id.clone(),
))?,
- redirection_data,
- mandate_reference: None,
+ redirection_data: Box::new(redirection_data),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: optional_correlation_id.clone(),
diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs
index c8758f5322c..d6f9117d786 100644
--- a/crates/router/src/connector/zsl/transformers.rs
+++ b/crates/router/src/connector/zsl/transformers.rs
@@ -328,12 +328,12 @@ impl<F, T>
status: enums::AttemptStatus::AuthenticationPending, // Redirect is always expected after success response
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(services::RedirectForm::Form {
+ redirection_data: Box::new(Some(services::RedirectForm::Form {
endpoint: redirect_url,
method: services::Method::Get,
form_fields: HashMap::new(),
- }),
- mandate_reference: None,
+ })),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
@@ -451,8 +451,8 @@ impl<F>
resource_id: types::ResponseId::ConnectorTransactionId(
item.response.txn_id.clone(),
),
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 545f94cfeb4..f49f4096340 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -2122,7 +2122,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_label: self.connector_label.clone(),
- connector_account_details: encrypted_data.connector_account_details,
+ connector_account_details: Box::new(encrypted_data.connector_account_details),
disabled,
payment_methods_enabled,
metadata: self.metadata,
@@ -2136,10 +2136,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
None => None,
},
applepay_verified_domains: None,
- pm_auth_config: self.pm_auth_config,
+ pm_auth_config: Box::new(self.pm_auth_config),
status: Some(connector_status),
- additional_merchant_data: encrypted_data.additional_merchant_data,
- connector_wallets_details: encrypted_data.connector_wallets_details,
+ additional_merchant_data: Box::new(encrypted_data.additional_merchant_data),
+ connector_wallets_details: Box::new(encrypted_data.connector_wallets_details),
})
}
}
@@ -2291,25 +2291,27 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
connector_name: None,
merchant_connector_id: None,
connector_label: self.connector_label.clone(),
- connector_account_details: encrypted_data.connector_account_details,
+ connector_account_details: Box::new(encrypted_data.connector_account_details),
test_mode: self.test_mode,
disabled,
payment_methods_enabled,
metadata: self.metadata,
frm_configs,
connector_webhook_details: match &self.connector_webhook_details {
- Some(connector_webhook_details) => connector_webhook_details
- .encode_to_value()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .map(Some)?
- .map(Secret::new),
- None => None,
+ Some(connector_webhook_details) => Box::new(
+ connector_webhook_details
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .map(Some)?
+ .map(Secret::new),
+ ),
+ None => Box::new(None),
},
applepay_verified_domains: None,
- pm_auth_config: self.pm_auth_config,
+ pm_auth_config: Box::new(self.pm_auth_config),
status: Some(connector_status),
- additional_merchant_data: encrypted_data.additional_merchant_data,
- connector_wallets_details: encrypted_data.connector_wallets_details,
+ additional_merchant_data: Box::new(encrypted_data.additional_merchant_data),
+ connector_wallets_details: Box::new(encrypted_data.connector_wallets_details),
})
}
}
diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs
index c3de228d9a7..5813a5bcd0c 100644
--- a/crates/router/src/core/connector_onboarding.rs
+++ b/crates/router/src/core/connector_onboarding.rs
@@ -95,7 +95,7 @@ pub async fn sync_onboarding_status(
.await?;
return Ok(ApplicationResponse::Json(api::OnboardingStatus::PayPal(
- api::PayPalOnboardingStatus::ConnectorIntegrated(update_mca_data),
+ api::PayPalOnboardingStatus::ConnectorIntegrated(Box::new(update_mca_data)),
)));
}
Ok(ApplicationResponse::Json(status))
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 19fbbf1952b..18cc8682eee 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -662,7 +662,7 @@ impl CustomerDeleteBridge for customers::GlobalId {
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: None,
- connector_customer: None,
+ connector_customer: Box::new(None),
default_billing_address: None,
default_shipping_address: None,
default_payment_method_id: None,
@@ -904,7 +904,7 @@ impl CustomerDeleteBridge for customers::CustomerId {
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: None,
- connector_customer: None,
+ connector_customer: Box::new(None),
address_id: None,
};
@@ -1204,7 +1204,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
description: self.description.clone(),
- connector_customer: None,
+ connector_customer: Box::new(None),
address_id: address.clone().map(|addr| addr.address_id),
},
key_store,
@@ -1296,7 +1296,7 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
description: self.description.clone(),
- connector_customer: None,
+ connector_customer: Box::new(None),
default_billing_address: encrypted_customer_billing_address.map(Into::into),
default_shipping_address: encrypted_customer_shipping_address.map(Into::into),
default_payment_method_id: Some(self.default_payment_method_id.clone()),
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index b5707979247..5ed3e910563 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -357,10 +357,10 @@ where
network_txn_id,
..
} => (mandate_reference.clone(), network_txn_id.clone()),
- _ => (None, None),
+ _ => (Box::new(None), None),
};
- let mandate_ids = mandate_reference
+ let mandate_ids = (*mandate_reference)
.as_ref()
.map(|md| {
md.encode_to_value()
@@ -379,7 +379,7 @@ where
mandate_ids,
network_txn_id,
get_insensitive_payment_method_data_if_exists(resp),
- mandate_reference,
+ *mandate_reference,
merchant_connector_id,
)?
else {
@@ -439,7 +439,7 @@ impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
match resp {
Ok(types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
- }) => mandate_reference,
+ }) => *mandate_reference,
_ => None,
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 2218197743a..b4acb98a7d4 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3071,9 +3071,9 @@ where
let should_continue = matches!(
router_data.response,
Ok(router_types::PaymentsResponseData::TransactionResponse {
- redirection_data: None,
+ ref redirection_data,
..
- })
+ }) if redirection_data.is_none()
) && router_data.status
!= common_enums::AttemptStatus::AuthenticationFailed;
(router_data, should_continue)
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 51cb5793adb..0de7683097b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1620,7 +1620,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
phone: Box::new(encryptable_customer.phone),
phone_country_code: request_customer_details.phone_country_code,
description: None,
- connector_customer: None,
+ connector_customer: Box::new(None),
metadata: None,
address_id: None,
};
@@ -3581,7 +3581,7 @@ pub async fn insert_merchant_connector_creds_to_config(
#[derive(Clone)]
pub enum MerchantConnectorAccountType {
- DbVal(domain::MerchantConnectorAccount),
+ DbVal(Box<domain::MerchantConnectorAccount>),
CacheVal(api_models::admin::MerchantConnectorDetails),
}
@@ -3795,7 +3795,7 @@ pub async fn get_merchant_connector_account(
todo!()
}
};
- mca.map(MerchantConnectorAccountType::DbVal)
+ mca.map(Box::new).map(MerchantConnectorAccountType::DbVal)
}
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 74339a88fb6..69cf19b09bb 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1496,7 +1496,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.event(AuditEvent::new(AuditEventType::PaymentConfirm {
client_src,
client_ver,
- frm_message,
+ frm_message: Box::new(frm_message),
}))
.with(payment_data.to_event())
.emit();
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index ae64fe41b1f..3e115ee74f0 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1500,7 +1500,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
let encoded_data = payment_data.payment_attempt.encoded_data.clone();
- let authentication_data = redirection_data
+ let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 060e93474b4..7fdccf9c60f 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -424,7 +424,7 @@ where
}) => {
let encoded_data = payment_data.get_payment_attempt().encoded_data.clone();
- let authentication_data = redirection_data
+ let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index b4e5ade5698..9809d40f7f6 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -157,10 +157,9 @@ where
let (connector_mandate_id, mandate_metadata) = match responses {
types::PaymentsResponseData::TransactionResponse {
- ref mandate_reference,
- ..
+ mandate_reference, ..
} => {
- if let Some(mandate_ref) = mandate_reference {
+ if let Some(ref mandate_ref) = *mandate_reference {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 58ea3b43462..66e5c996d34 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -436,8 +436,8 @@ where
// [#44]: why should response be filled during request
let response = Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
- redirection_data: None,
- mandate_reference: None,
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index c1b8f78eeb1..02c619b68d9 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -375,7 +375,7 @@ pub async fn payouts_confirm_core(
&merchant_account,
None,
&key_store,
- &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),
+ &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
locale,
)
.await?;
@@ -448,7 +448,7 @@ pub async fn payouts_update_core(
&merchant_account,
None,
&key_store,
- &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()),
+ &payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
locale,
)
.await?;
diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs
index 8193109c250..a51b6c86a34 100644
--- a/crates/router/src/core/verification/utils.rs
+++ b/crates/router/src/core/verification/utils.rs
@@ -68,36 +68,36 @@ pub async fn check_existence_and_add_domain_to_db(
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_name: None,
- connector_account_details: None,
+ connector_account_details: Box::new(None),
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
- connector_webhook_details: None,
+ connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
- pm_auth_config: None,
+ pm_auth_config: Box::new(None),
connector_label: None,
status: None,
- connector_wallets_details: None,
- additional_merchant_data: None,
+ connector_wallets_details: Box::new(None),
+ additional_merchant_data: Box::new(None),
};
#[cfg(feature = "v2")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
- connector_account_details: None,
+ connector_account_details: Box::new(None),
disabled: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: None,
applepay_verified_domains: Some(already_verified_domains.clone()),
- pm_auth_config: None,
+ pm_auth_config: Box::new(None),
connector_label: None,
status: None,
- connector_wallets_details: None,
- additional_merchant_data: None,
+ connector_wallets_details: Box::new(None),
+ additional_merchant_data: Box::new(None),
};
state
.store
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 66de5106e6f..3627438547c 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -613,7 +613,7 @@ async fn payments_incoming_webhook_flow(
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
- api::OutgoingWebhookContent::PaymentDetails(payments_response),
+ api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
@@ -745,7 +745,7 @@ async fn payouts_incoming_webhook_flow(
enums::EventClass::Payouts,
updated_payout_attempt.payout_id.clone(),
enums::EventObjectType::PayoutDetails,
- api::OutgoingWebhookContent::PayoutDetails(payout_create_response),
+ api::OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),
Some(updated_payout_attempt.created_at),
))
.await?;
@@ -852,7 +852,7 @@ async fn refunds_incoming_webhook_flow(
enums::EventClass::Refunds,
refund_id,
enums::EventObjectType::RefundDetails,
- api::OutgoingWebhookContent::RefundDetails(refund_response),
+ api::OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
Some(updated_refund.created_at),
))
.await?;
@@ -1128,7 +1128,9 @@ async fn external_authentication_incoming_webhook_flow(
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
- api::OutgoingWebhookContent::PaymentDetails(payments_response),
+ api::OutgoingWebhookContent::PaymentDetails(Box::new(
+ payments_response,
+ )),
primary_object_created_at,
))
.await?;
@@ -1334,7 +1336,7 @@ async fn frm_incoming_webhook_flow(
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
- api::OutgoingWebhookContent::PaymentDetails(payments_response),
+ api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
@@ -1498,7 +1500,7 @@ async fn bank_transfer_webhook_flow(
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
- api::OutgoingWebhookContent::PaymentDetails(payments_response),
+ api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index fbf69278357..0a9c17ed3a0 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -361,7 +361,7 @@ async fn trigger_webhook_to_merchant(
&event_id,
client_error,
delivery_attempt,
- ScheduleWebhookRetry::WithProcessTracker(process_tracker),
+ ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
@@ -391,7 +391,7 @@ async fn trigger_webhook_to_merchant(
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
- ScheduleWebhookRetry::WithProcessTracker(process_tracker),
+ ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
@@ -668,7 +668,7 @@ pub(crate) fn get_outgoing_webhook_request(
#[derive(Debug)]
enum ScheduleWebhookRetry {
- WithProcessTracker(storage::ProcessTracker),
+ WithProcessTracker(Box<storage::ProcessTracker>),
NoSchedule,
}
@@ -757,7 +757,7 @@ async fn api_client_error_handler(
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
- process_tracker,
+ *process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
@@ -903,7 +903,7 @@ async fn error_response_handler(
outgoing_webhook_retry::retry_webhook_delivery_task(
&*state.store,
merchant_id,
- process_tracker,
+ *process_tracker,
)
.await
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)?;
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index 8680e43eff3..3d71f5f5553 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -64,7 +64,7 @@ pub async fn construct_webhook_router_data<'a>(
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> {
let auth_type: types::ConnectorAuthType =
- helpers::MerchantConnectorAccountType::DbVal(merchant_connector_account.clone())
+ helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 34a7c69d91a..64b52b7995e 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -14,8 +14,8 @@ const INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT: i64 = 100;
#[derive(Debug)]
enum MerchantAccountOrProfile {
- MerchantAccount(domain::MerchantAccount),
- Profile(domain::Profile),
+ MerchantAccount(Box<domain::MerchantAccount>),
+ Profile(Box<domain::Profile>),
}
#[instrument(skip(state))]
@@ -302,7 +302,7 @@ async fn get_account_and_key_store(
})?;
Ok((
- MerchantAccountOrProfile::Profile(business_profile),
+ MerchantAccountOrProfile::Profile(Box::new(business_profile)),
merchant_key_store,
))
}
@@ -318,7 +318,7 @@ async fn get_account_and_key_store(
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((
- MerchantAccountOrProfile::MerchantAccount(merchant_account),
+ MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)),
merchant_key_store,
))
}
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 3a8750feff9..2e2bb7dccbb 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -493,12 +493,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::AddressUpdate(Box::new(
+ updatable: Box::new(kv::Updateable::AddressUpdate(Box::new(
kv::AddressUpdateMems {
orig: address,
update_data: address_update.into(),
},
- )),
+ ))),
},
};
@@ -597,7 +597,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Address(Box::new(address_new)),
+ insertable: Box::new(kv::Insertable::Address(Box::new(address_new))),
},
};
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 5020c238e4a..ae23f81e2ea 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -446,10 +446,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
- orig: customer,
- update_data: customer_update.into(),
- }),
+ updatable: Box::new(kv::Updateable::CustomerUpdate(
+ kv::CustomerUpdateMems {
+ orig: customer,
+ update_data: customer_update.into(),
+ },
+ )),
},
};
@@ -689,7 +691,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Customer(new_customer.clone()),
+ insertable: Box::new(kv::Insertable::Customer(new_customer.clone())),
},
};
let storage_customer = new_customer.into();
@@ -768,7 +770,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Customer(new_customer.clone()),
+ insertable: Box::new(kv::Insertable::Customer(new_customer.clone())),
},
};
let storage_customer = new_customer.into();
@@ -931,10 +933,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
- orig: customer,
- update_data: customer_update.into(),
- }),
+ updatable: Box::new(kv::Updateable::CustomerUpdate(
+ kv::CustomerUpdateMems {
+ orig: customer,
+ update_data: customer_update.into(),
+ },
+ )),
},
};
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index 95733805b43..076cb768e61 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -274,10 +274,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::MandateUpdate(kv::MandateUpdateMems {
- orig: mandate,
- update_data: m_update,
- }),
+ updatable: Box::new(kv::Updateable::MandateUpdate(
+ kv::MandateUpdateMems {
+ orig: mandate,
+ update_data: m_update,
+ },
+ )),
},
};
@@ -346,7 +348,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Mandate(mandate),
+ insertable: Box::new(kv::Insertable::Mandate(mandate)),
},
};
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index e75fb940a35..ac66ed707f1 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -496,7 +496,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::PaymentMethod(payment_method_new),
+ insertable: Box::new(kv::Insertable::PaymentMethod(payment_method_new)),
},
};
@@ -588,12 +588,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentMethodUpdate(
+ updatable: Box::new(kv::Updateable::PaymentMethodUpdate(Box::new(
kv::PaymentMethodUpdateMems {
orig: payment_method,
update_data: p_update,
},
- ),
+ ))),
},
};
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 41cb3cef5c6..745170d7075 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -445,7 +445,7 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Refund(new),
+ insertable: Box::new(kv::Insertable::Refund(new)),
},
};
@@ -617,10 +617,12 @@ mod storage {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::RefundUpdate(kv::RefundUpdateMems {
- orig: this,
- update_data: refund,
- }),
+ updatable: Box::new(kv::Updateable::RefundUpdate(
+ kv::RefundUpdateMems {
+ orig: this,
+ update_data: refund,
+ },
+ )),
},
};
diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs
index 06bd84675b1..c022c70d9e2 100644
--- a/crates/router/src/db/reverse_lookup.rs
+++ b/crates/router/src/db/reverse_lookup.rs
@@ -116,7 +116,7 @@ mod storage {
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::ReverseLookUp(new),
+ insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 367a573a93b..9b7a688f7eb 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -18,7 +18,7 @@ pub enum AuditEventType {
PaymentConfirm {
client_src: Option<String>,
client_ver: Option<String>,
- frm_message: Option<FraudCheck>,
+ frm_message: Box<Option<FraudCheck>>,
},
PaymentCancelled {
cancellation_reason: Option<String>,
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index a54c2bc8ad6..f56a741dc1a 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1166,9 +1166,9 @@ where
diesel_models::enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
diesel_models::enums::EventObjectType::PaymentDetails,
- webhooks::OutgoingWebhookContent::PaymentDetails(
+ webhooks::OutgoingWebhookContent::PaymentDetails(Box::new(
payments_response_json,
- ),
+ )),
primary_object_created_at,
))
.await
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index eb4530bbe54..1bfcc8ebe7b 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -423,7 +423,7 @@ async fn get_outgoing_webhook_content_and_event_type(
logger::debug!(current_resource_status=%payments_response.status);
Ok((
- OutgoingWebhookContent::PaymentDetails(payments_response),
+ OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
event_type,
))
}
@@ -449,7 +449,7 @@ async fn get_outgoing_webhook_content_and_event_type(
let refund_response = RefundResponse::foreign_from(refund);
Ok((
- OutgoingWebhookContent::RefundDetails(refund_response),
+ OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
event_type,
))
}
@@ -548,7 +548,7 @@ async fn get_outgoing_webhook_content_and_event_type(
logger::debug!(current_resource_status=%payout_data.payout_attempt.status);
Ok((
- OutgoingWebhookContent::PayoutDetails(payout_create_response),
+ OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),
event_type,
))
}
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index 54377e45267..eec85e267b9 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -93,7 +93,7 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::ReverseLookUp(new),
+ insertable: Box::new(kv::Insertable::ReverseLookUp(new)),
},
};
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 36a9da5944b..552630a0f76 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -538,9 +538,9 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::PaymentAttempt(
+ insertable: Box::new(kv::Insertable::PaymentAttempt(Box::new(
payment_attempt.to_storage_model(),
- ),
+ ))),
},
};
@@ -645,12 +645,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentAttemptUpdate(
+ updatable: Box::new(kv::Updateable::PaymentAttemptUpdate(Box::new(
kv::PaymentAttemptUpdateMems {
orig: this.clone().to_storage_model(),
update_data: payment_attempt.to_storage_model(),
},
- ),
+ ))),
},
};
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 8ca63e79037..3fcd30f1e89 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -103,7 +103,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::PaymentIntent(new_payment_intent),
+ insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
+ new_payment_intent,
+ ))),
},
};
@@ -219,12 +221,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentIntentUpdate(
+ updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
kv::PaymentIntentUpdateMems {
orig: origin_diesel_intent,
update_data: diesel_intent_update,
},
- ),
+ ))),
},
};
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 81d06a1cbd5..3ac66a2c301 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -93,9 +93,9 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::PayoutAttempt(
+ insertable: Box::new(kv::Insertable::PayoutAttempt(
new_payout_attempt.to_storage_model(),
- ),
+ )),
},
};
@@ -182,12 +182,12 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::PayoutAttemptUpdate(
+ updatable: Box::new(kv::Updateable::PayoutAttemptUpdate(
kv::PayoutAttemptUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
},
- ),
+ )),
},
};
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 9a94743da3f..2f6540732fd 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -130,7 +130,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
- insertable: kv::Insertable::Payouts(new.to_storage_model()),
+ insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())),
},
};
@@ -201,10 +201,10 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
- updatable: kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems {
+ updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
- }),
+ })),
},
};
|
2024-10-22T13:48:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR addresses the clippy lints occurring due to new rust version 1.82.0.
Majorly addresses below warning -

### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
673b8691e092e145ba211050db4f5c7e021a0ce2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6354
|
Bug: Refactor: add deep health check for dynamic routing
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 191f2ba7f8b..12df81d82c9 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -789,3 +789,4 @@ 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
+service = "dynamo" # Service name
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 0eab330652a..fa0c0484a77 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -326,3 +326,4 @@ check_token_status_url= "" # base url to check token status from token servic
[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
host = "localhost" # Client Host
port = 7000 # Client Port
+service = "dynamo" # Service name
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index e8668aab502..a5d702e26fb 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -20,6 +20,7 @@ v1 = ["common_utils/v1"]
v2 = ["common_utils/v2", "customer_v2"]
customer_v2 = ["common_utils/customer_v2"]
payment_methods_v2 = ["common_utils/payment_methods_v2"]
+dynamic_routing = []
[dependencies]
actix-web = { version = "4.5.1", optional = true }
diff --git a/crates/api_models/src/health_check.rs b/crates/api_models/src/health_check.rs
index 1e86e2964c7..4a1c009e43e 100644
--- a/crates/api_models/src/health_check.rs
+++ b/crates/api_models/src/health_check.rs
@@ -1,3 +1,4 @@
+use std::collections::hash_map::HashMap;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RouterHealthCheckResponse {
pub database: bool,
@@ -9,10 +10,22 @@ pub struct RouterHealthCheckResponse {
#[cfg(feature = "olap")]
pub opensearch: bool,
pub outgoing_request: bool,
+ #[cfg(feature = "dynamic_routing")]
+ pub grpc_health_check: HealthCheckMap,
}
impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {}
+/// gRPC based services eligible for Health check
+#[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum HealthCheckServices {
+ /// Dynamic routing service
+ DynamicRoutingService,
+}
+
+pub type HealthCheckMap = HashMap<HealthCheckServices, bool>;
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SchedulerHealthCheckResponse {
pub database: bool,
diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs
index 605ef699715..0a4938e94b4 100644
--- a/crates/external_services/build.rs
+++ b/crates/external_services/build.rs
@@ -3,11 +3,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "dynamic_routing")]
{
// Get the directory of the current crate
- let proto_file = router_env::workspace_path()
- .join("proto")
- .join("success_rate.proto");
+
+ let proto_path = router_env::workspace_path().join("proto");
+ let success_rate_proto_file = proto_path.join("success_rate.proto");
+
+ let health_check_proto_file = proto_path.join("health_check.proto");
+ let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?);
+
// Compile the .proto file
- tonic_build::compile_protos(proto_file).expect("Failed to compile success rate proto file");
+ tonic_build::configure()
+ .out_dir(out_dir)
+ .compile(
+ &[success_rate_proto_file, health_check_proto_file],
+ &[proto_path],
+ )
+ .expect("Failed to compile proto files");
}
Ok(())
}
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs
index e7b229a8070..8981a1094d6 100644
--- a/crates/external_services/src/grpc_client.rs
+++ b/crates/external_services/src/grpc_client.rs
@@ -1,11 +1,28 @@
/// Dyanimc Routing Client interface implementation
#[cfg(feature = "dynamic_routing")]
pub mod dynamic_routing;
+/// gRPC based Heath Check Client interface implementation
+#[cfg(feature = "dynamic_routing")]
+pub mod health_check_client;
use std::{fmt::Debug, sync::Arc};
#[cfg(feature = "dynamic_routing")]
use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy};
+#[cfg(feature = "dynamic_routing")]
+use health_check_client::HealthCheckClient;
+#[cfg(feature = "dynamic_routing")]
+use http_body_util::combinators::UnsyncBoxBody;
+#[cfg(feature = "dynamic_routing")]
+use hyper::body::Bytes;
+#[cfg(feature = "dynamic_routing")]
+use hyper_util::client::legacy::connect::HttpConnector;
use serde;
+#[cfg(feature = "dynamic_routing")]
+use tonic::Status;
+
+#[cfg(feature = "dynamic_routing")]
+/// Hyper based Client type for maintaining connection pool for all gRPC services
+pub type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>;
/// Struct contains all the gRPC Clients
#[derive(Debug, Clone)]
@@ -13,6 +30,9 @@ pub struct GrpcClients {
/// The routing client
#[cfg(feature = "dynamic_routing")]
pub dynamic_routing: RoutingStrategy,
+ /// Health Check client for all gRPC services
+ #[cfg(feature = "dynamic_routing")]
+ pub health_client: HealthCheckClient,
}
/// Type that contains the configs required to construct a gRPC client with its respective services.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
@@ -29,17 +49,30 @@ impl GrpcClientSettings {
/// 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 client =
+ hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
+ .http2_only(true)
+ .build_http();
+
#[cfg(feature = "dynamic_routing")]
let dynamic_routing_connection = self
.dynamic_routing_client
.clone()
- .get_dynamic_routing_connection()
+ .get_dynamic_routing_connection(client.clone())
.await
.expect("Failed to establish a connection with the Dynamic Routing Server");
+ #[cfg(feature = "dynamic_routing")]
+ let health_client = HealthCheckClient::build_connections(self, client)
+ .await
+ .expect("Failed to build gRPC connections");
+
Arc::new(GrpcClients {
#[cfg(feature = "dynamic_routing")]
dynamic_routing: dynamic_routing_connection,
+ #[cfg(feature = "dynamic_routing")]
+ health_client,
})
}
}
diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs
index 3264f065b51..7ec42de0d7c 100644
--- a/crates/external_services/src/grpc_client/dynamic_routing.rs
+++ b/crates/external_services/src/grpc_client/dynamic_routing.rs
@@ -6,9 +6,6 @@ use api_models::routing::{
};
use common_utils::{errors::CustomResult, ext_traits::OptionExt, transformers::ForeignTryFrom};
use error_stack::ResultExt;
-use http_body_util::combinators::UnsyncBoxBody;
-use hyper::body::Bytes;
-use hyper_util::client::legacy::connect::HttpConnector;
use router_env::logger;
use serde;
use success_rate::{
@@ -18,7 +15,8 @@ use success_rate::{
InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig,
UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse,
};
-use tonic::Status;
+
+use super::Client;
#[allow(
missing_docs,
unused_qualifications,
@@ -45,8 +43,6 @@ pub enum DynamicRoutingError {
SuccessRateBasedRoutingFailure(String),
}
-type Client = hyper_util::client::legacy::Client<HttpConnector, UnsyncBoxBody<Bytes, Status>>;
-
/// Type that consists of all the services provided by the client
#[derive(Debug, Clone)]
pub struct RoutingStrategy {
@@ -64,6 +60,8 @@ pub enum DynamicRoutingClientConfig {
host: String,
/// The port of the client
port: u16,
+ /// Service name
+ service: String,
},
#[default]
/// If the dynamic routing client config has been disabled
@@ -74,13 +72,10 @@ impl DynamicRoutingClientConfig {
/// establish connection with the server
pub async fn get_dynamic_routing_connection(
self,
+ client: Client,
) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {
- let client =
- hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
- .http2_only(true)
- .build_http();
let success_rate_client = match self {
- Self::Enabled { host, port } => {
+ Self::Enabled { host, port, .. } => {
let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?;
logger::info!("Connection established with dynamic routing gRPC Server");
Some(SuccessRateCalculatorClient::with_origin(client, uri))
diff --git a/crates/external_services/src/grpc_client/health_check_client.rs b/crates/external_services/src/grpc_client/health_check_client.rs
new file mode 100644
index 00000000000..94d78df7955
--- /dev/null
+++ b/crates/external_services/src/grpc_client/health_check_client.rs
@@ -0,0 +1,149 @@
+use std::{collections::HashMap, fmt::Debug};
+
+use api_models::health_check::{HealthCheckMap, HealthCheckServices};
+use common_utils::{errors::CustomResult, ext_traits::AsyncExt};
+use error_stack::ResultExt;
+pub use health_check::{
+ health_check_response::ServingStatus, health_client::HealthClient, HealthCheckRequest,
+ HealthCheckResponse,
+};
+use router_env::logger;
+
+#[allow(
+ missing_docs,
+ unused_qualifications,
+ clippy::unwrap_used,
+ clippy::as_conversions,
+ clippy::use_self
+)]
+pub mod health_check {
+ tonic::include_proto!("grpc.health.v1");
+}
+
+use super::{Client, DynamicRoutingClientConfig, GrpcClientSettings};
+
+/// Result type for Dynamic Routing
+pub type HealthCheckResult<T> = CustomResult<T, HealthCheckError>;
+/// Dynamic Routing Errors
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum HealthCheckError {
+ /// The required input is missing
+ #[error("Missing fields: {0} for building the Health check connection")]
+ MissingFields(String),
+ /// Error from gRPC Server
+ #[error("Error from gRPC Server : {0}")]
+ ConnectionError(String),
+ /// status is invalid
+ #[error("Invalid Status from server")]
+ InvalidStatus,
+}
+
+/// Health Check Client type
+#[derive(Debug, Clone)]
+pub struct HealthCheckClient {
+ /// Health clients for all gRPC based services
+ pub clients: HashMap<HealthCheckServices, HealthClient<Client>>,
+}
+
+impl HealthCheckClient {
+ /// Build connections to all gRPC services
+ pub async fn build_connections(
+ config: &GrpcClientSettings,
+ client: Client,
+ ) -> Result<Self, Box<dyn std::error::Error>> {
+ let dynamic_routing_config = &config.dynamic_routing_client;
+ let connection = match dynamic_routing_config {
+ DynamicRoutingClientConfig::Enabled {
+ host,
+ port,
+ service,
+ } => Some((host.clone(), *port, service.clone())),
+ _ => None,
+ };
+
+ let mut client_map = HashMap::new();
+
+ if let Some(conn) = connection {
+ let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?;
+ let health_client = HealthClient::with_origin(client, uri);
+
+ client_map.insert(HealthCheckServices::DynamicRoutingService, health_client);
+ }
+
+ Ok(Self {
+ clients: client_map,
+ })
+ }
+ /// Perform health check for all services involved
+ pub async fn perform_health_check(
+ &self,
+ config: &GrpcClientSettings,
+ ) -> HealthCheckResult<HealthCheckMap> {
+ let dynamic_routing_config = &config.dynamic_routing_client;
+ let connection = match dynamic_routing_config {
+ DynamicRoutingClientConfig::Enabled {
+ host,
+ port,
+ service,
+ } => Some((host.clone(), *port, service.clone())),
+ _ => None,
+ };
+
+ let health_client = self
+ .clients
+ .get(&HealthCheckServices::DynamicRoutingService);
+
+ // SAFETY : This is a safe cast as there exists a valid
+ // integer value for this variant
+ #[allow(clippy::as_conversions)]
+ let expected_status = ServingStatus::Serving as i32;
+
+ let mut service_map = HealthCheckMap::new();
+
+ let health_check_succeed = connection
+ .as_ref()
+ .async_map(|conn| self.get_response_from_grpc_service(conn.2.clone(), health_client))
+ .await
+ .transpose()
+ .change_context(HealthCheckError::ConnectionError(
+ "error calling dynamic routing service".to_string(),
+ ))
+ .map_err(|err| logger::error!(error=?err))
+ .ok()
+ .flatten()
+ .is_some_and(|resp| resp.status == expected_status);
+
+ connection.and_then(|_conn| {
+ service_map.insert(
+ HealthCheckServices::DynamicRoutingService,
+ health_check_succeed,
+ )
+ });
+
+ Ok(service_map)
+ }
+
+ async fn get_response_from_grpc_service(
+ &self,
+ service: String,
+ client: Option<&HealthClient<Client>>,
+ ) -> HealthCheckResult<HealthCheckResponse> {
+ let request = tonic::Request::new(HealthCheckRequest { service });
+
+ let mut client = client
+ .ok_or(HealthCheckError::MissingFields(
+ "[health_client]".to_string(),
+ ))?
+ .clone();
+
+ let response = client
+ .check(request)
+ .await
+ .change_context(HealthCheckError::ConnectionError(
+ "Failed to call dynamic routing service".to_string(),
+ ))?
+ .into_inner();
+
+ Ok(response)
+ }
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index b794443a047..f6e1f0efc69 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -37,7 +37,7 @@ v2 = ["customer_v2", "payment_methods_v2", "common_default", "api_models/v2", "d
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
-dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing"]
+dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/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/core/health_check.rs b/crates/router/src/core/health_check.rs
index 83faee677d4..31e8cc75f5b 100644
--- a/crates/router/src/core/health_check.rs
+++ b/crates/router/src/core/health_check.rs
@@ -1,5 +1,7 @@
#[cfg(feature = "olap")]
use analytics::health_check::HealthCheck;
+#[cfg(feature = "dynamic_routing")]
+use api_models::health_check::HealthCheckMap;
use api_models::health_check::HealthState;
use error_stack::ResultExt;
use router_env::logger;
@@ -28,6 +30,11 @@ pub trait HealthCheckInterface {
async fn health_check_opensearch(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError>;
+
+ #[cfg(feature = "dynamic_routing")]
+ async fn health_check_grpc(
+ &self,
+ ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>;
}
#[async_trait::async_trait]
@@ -158,4 +165,20 @@ impl HealthCheckInterface for app::SessionState {
logger::debug!("Outgoing request successful");
Ok(HealthState::Running)
}
+
+ #[cfg(feature = "dynamic_routing")]
+ async fn health_check_grpc(
+ &self,
+ ) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError> {
+ let health_client = &self.grpc_client.health_client;
+ let grpc_config = &self.conf.grpc_client;
+
+ let health_check_map = health_client
+ .perform_health_check(grpc_config)
+ .await
+ .change_context(errors::HealthCheckGRPCServiceError::FailedToCallService)?;
+
+ logger::debug!("Health check successful");
+ Ok(health_check_map)
+ }
}
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index c1cf28d00ad..0f2e6333647 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -95,6 +95,19 @@ async fn deep_health_check_func(
logger::debug!("Analytics health check end");
+ logger::debug!("gRPC health check begin");
+
+ #[cfg(feature = "dynamic_routing")]
+ let grpc_health_check = state.health_check_grpc().await.map_err(|error| {
+ let message = error.to_string();
+ error.change_context(errors::ApiErrorResponse::HealthCheckError {
+ component: "gRPC services",
+ message,
+ })
+ })?;
+
+ logger::debug!("gRPC health check end");
+
logger::debug!("Opensearch health check begin");
#[cfg(feature = "olap")]
@@ -129,6 +142,8 @@ async fn deep_health_check_func(
#[cfg(feature = "olap")]
opensearch: opensearch_status.into(),
outgoing_request: outgoing_check.into(),
+ #[cfg(feature = "dynamic_routing")]
+ grpc_health_check,
};
Ok(api::ApplicationResponse::Json(response))
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 1cee96f49eb..10d7f4dc8e8 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -292,3 +292,9 @@ pub enum HealthCheckLockerError {
#[error("Failed to establish Locker connection")]
FailedToCallLocker,
}
+
+#[derive(Debug, Clone, thiserror::Error)]
+pub enum HealthCheckGRPCServiceError {
+ #[error("Failed to establish connection with gRPC service")]
+ FailedToCallService,
+}
diff --git a/proto/health_check.proto b/proto/health_check.proto
new file mode 100644
index 00000000000..b246f59f690
--- /dev/null
+++ b/proto/health_check.proto
@@ -0,0 +1,21 @@
+syntax = "proto3";
+
+package grpc.health.v1;
+
+message HealthCheckRequest {
+ string service = 1;
+}
+
+message HealthCheckResponse {
+ enum ServingStatus {
+ UNKNOWN = 0;
+ SERVING = 1;
+ NOT_SERVING = 2;
+ SERVICE_UNKNOWN = 3; // Used only by the Watch method.
+ }
+ ServingStatus status = 1;
+}
+
+service Health {
+ rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
+}
\ No newline at end of file
|
2024-10-25T19:11:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Implemented gRPC based health check
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested locally
```
curl --location --request GET 'http://localhost:8080/health/ready' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Li5BLbzNIHjf2t0J6kYgS7sQurtmLubs1sGAxTE6MVo59aMBEMDSK6Qt8me7kJZQ'
```
Response
```
{
"database": true,
"redis": true,
"analytics": true,
"opensearch": true,
"outgoing_request": true,
"grpc_health_check": {
"dynamic_routing_service": true
}
}
```
<img width="1345" alt="image" src="https://github.com/user-attachments/assets/aaae7e48-63b4-4dfc-b9c0-832dfe569469">
Response when runtime config is disabled
```
{
"database": true,
"redis": true,
"analytics": true,
"opensearch": true,
"outgoing_request": true,
"grpc_health_check": {}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ea81432e3eb72d9a2e139e26741a42cdd8d31202
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6343
|
Bug: feat(analytics): add customer_id as filter for payment intents
Add customer_id as a filter for payment intents
|
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index af46baed23e..3e8915c60a2 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -205,7 +205,8 @@ pub async fn get_metrics(
| PaymentIntentMetrics::SessionizedPaymentsSuccessRate => metrics_builder
.payments_success_rate
.add_metrics_bucket(&value),
- PaymentIntentMetrics::SessionizedPaymentProcessedAmount => metrics_builder
+ PaymentIntentMetrics::SessionizedPaymentProcessedAmount
+ | PaymentIntentMetrics::PaymentProcessedAmount => metrics_builder
.payment_processed_amount
.add_metrics_bucket(&value),
PaymentIntentMetrics::SessionizedPaymentsDistribution => metrics_builder
diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs
index e81b050214c..d03d6c2a15f 100644
--- a/crates/analytics/src/payment_intents/filters.rs
+++ b/crates/analytics/src/payment_intents/filters.rs
@@ -54,4 +54,5 @@ pub struct PaymentIntentFilterRow {
pub status: Option<DBEnumWrapper<IntentStatus>>,
pub currency: Option<DBEnumWrapper<Currency>>,
pub profile_id: Option<String>,
+ pub customer_id: Option<String>,
}
diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs
index e9d7f244306..9aa7d3e9771 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -17,6 +17,7 @@ use crate::{
};
mod payment_intent_count;
+mod payment_processed_amount;
mod payments_success_rate;
mod sessionized_metrics;
mod smart_retried_amount;
@@ -24,6 +25,7 @@ mod successful_smart_retries;
mod total_smart_retries;
use payment_intent_count::PaymentIntentCount;
+use payment_processed_amount::PaymentProcessedAmount;
use payments_success_rate::PaymentsSuccessRate;
use smart_retried_amount::SmartRetriedAmount;
use successful_smart_retries::SuccessfulSmartRetries;
@@ -107,6 +109,11 @@ where
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
+ Self::PaymentProcessedAmount => {
+ PaymentProcessedAmount
+ .load_metrics(dimensions, auth, filters, granularity, time_range, pool)
+ .await
+ }
Self::SessionizedSuccessfulSmartRetries => {
sessionized_metrics::SuccessfulSmartRetries
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
diff --git a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs
new file mode 100644
index 00000000000..51b574f4ad3
--- /dev/null
+++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs
@@ -0,0 +1,161 @@
+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(super) 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::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")
+ .switch()?;
+
+ query_builder.add_select_column("currency").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()?;
+
+ query_builder
+ .add_group_by_clause("currency")
+ .attach_printable("Error grouping by currency")
+ .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(),
+ 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/types.rs b/crates/analytics/src/payment_intents/types.rs
index 03f2a196c20..bb5141297c5 100644
--- a/crates/analytics/src/payment_intents/types.rs
+++ b/crates/analytics/src/payment_intents/types.rs
@@ -30,6 +30,11 @@ where
.add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id)
.attach_printable("Error adding profile id filter")?;
}
+ if !self.customer_id.is_empty() {
+ builder
+ .add_filter_in_range_clause("customer_id", &self.customer_id)
+ .attach_printable("Error adding customer id filter")?;
+ }
Ok(())
}
}
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index 7ce338f7db3..d746594e36e 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -451,6 +451,12 @@ impl<T: AnalyticsDataSource> ToSql<T> for &common_utils::id_type::PaymentId {
}
}
+impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId {
+ fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
+ Ok(self.get_string_repr().to_owned())
+ }
+}
+
/// Implement `ToSql` on arrays of types that impl `ToString`.
macro_rules! impl_to_sql_for_to_string {
($($type:ty),+) => {
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 89eb2ee0bde..7c90e37c55f 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -652,10 +652,15 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi
ColumnNotFound(_) => Ok(Default::default()),
e => Err(e),
})?;
+ let customer_id: Option<String> = row.try_get("customer_id").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
Ok(Self {
status,
currency,
profile_id,
+ customer_id,
})
}
}
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs
index d018437ae8c..60662f2e90a 100644
--- a/crates/api_models/src/analytics/payment_intents.rs
+++ b/crates/api_models/src/analytics/payment_intents.rs
@@ -16,6 +16,8 @@ pub struct PaymentIntentFilters {
pub currency: Vec<Currency>,
#[serde(default)]
pub profile_id: Vec<id_type::ProfileId>,
+ #[serde(default)]
+ pub customer_id: Vec<id_type::CustomerId>,
}
#[derive(
@@ -62,6 +64,7 @@ pub enum PaymentIntentMetrics {
SmartRetriedAmount,
PaymentIntentCount,
PaymentsSuccessRate,
+ PaymentProcessedAmount,
SessionizedSuccessfulSmartRetries,
SessionizedTotalSmartRetries,
SessionizedSmartRetriedAmount,
|
2024-10-17T06:31:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Added `customer_id` as a filter for payment intents
- Added `payment_processed_amount` metric for `payment_intents` table
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Filter out payments for a particular customer through the `customer_id`
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Hit the curl:
Metric data would be obtained based on the customer_id filter applied.
```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyOTI0ODM1MCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.TQD6wYkiTXlTvPW3-mH8FzEP1d7hXw9SmWgjVMH7flk' \
--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"
},
"filters": {
"customer_id": ["StripeCustomer"]
},
"mode": "ORDER",
"source": "BATCH",
"metrics": [
"payment_processed_amount"
]
}
]'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
829a20cc933267551e49565d06eb08e03e5f13bb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6336
|
Bug: Create an id type for API Key ID
Currently `key_id` is a String. We need to create an `id_type` for it and migrate all occurrences accordingly
|
diff --git a/.typos.toml b/.typos.toml
index 79c86a39c6b..d2ffb8a5b10 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -1,5 +1,8 @@
[default]
check-filename = true
+extend-ignore-identifiers-re = [
+ "UE_[0-9]{3,4}", # Unified error codes
+]
[default.extend-identifiers]
ABD = "ABD" # Aberdeenshire, UK ISO 3166-2 code
@@ -38,7 +41,6 @@ ws2ipdef = "ws2ipdef" # WinSock Extension
ws2tcpip = "ws2tcpip" # WinSock Extension
ZAR = "ZAR" # South African Rand currency code
JOD = "JOD" # Jordan currency code
-UE_000 = "UE_000" #default unified error code
[default.extend-words]
diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs
index 65cc6b9a25a..d25cd989b0f 100644
--- a/crates/api_models/src/api_keys.rs
+++ b/crates/api_models/src/api_keys.rs
@@ -29,8 +29,8 @@ pub struct CreateApiKeyRequest {
#[derive(Debug, Serialize, ToSchema)]
pub struct CreateApiKeyResponse {
/// The identifier for the API Key.
- #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")]
- pub key_id: String,
+ #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
+ pub key_id: common_utils::id_type::ApiKeyId,
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
@@ -72,8 +72,8 @@ pub struct CreateApiKeyResponse {
#[derive(Debug, Serialize, ToSchema)]
pub struct RetrieveApiKeyResponse {
/// The identifier for the API Key.
- #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")]
- pub key_id: String,
+ #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
+ pub key_id: common_utils::id_type::ApiKeyId,
/// The identifier for the Merchant Account.
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
@@ -131,7 +131,8 @@ pub struct UpdateApiKeyRequest {
pub expiration: Option<ApiKeyExpiration>,
#[serde(skip_deserializing)]
- pub key_id: String,
+ #[schema(value_type = String)]
+ pub key_id: common_utils::id_type::ApiKeyId,
#[serde(skip_deserializing)]
#[schema(value_type = String)]
@@ -146,8 +147,8 @@ pub struct RevokeApiKeyResponse {
pub merchant_id: common_utils::id_type::MerchantId,
/// The identifier for the API Key.
- #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")]
- pub key_id: String,
+ #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)]
+ pub key_id: common_utils::id_type::ApiKeyId,
/// Indicates whether the API key was revoked or not.
#[schema(example = "true")]
pub revoked: bool,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 2b1571617e8..ffeff7f2f2a 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -40,6 +40,9 @@ pub enum ApiEventsType {
BusinessProfile {
profile_id: id_type::ProfileId,
},
+ ApiKey {
+ key_id: id_type::ApiKeyId,
+ },
User {
user_id: String,
},
@@ -124,10 +127,6 @@ impl_api_event_type!(
(
String,
id_type::MerchantId,
- (id_type::MerchantId, String),
- (id_type::MerchantId, &String),
- (&id_type::MerchantId, &String),
- (&String, &String),
(Option<i64>, Option<i64>, String),
(Option<i64>, Option<i64>, id_type::MerchantId),
bool
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 78e3841690a..c256559fc1c 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -3,6 +3,7 @@
use std::{borrow::Cow, fmt::Debug};
+mod api_key;
mod customer;
mod merchant;
mod merchant_connector_account;
@@ -14,6 +15,7 @@ mod routing;
#[cfg(feature = "v2")]
mod global_id;
+pub use api_key::ApiKeyId;
pub use customer::CustomerId;
use diesel::{
backend::Backend,
diff --git a/crates/common_utils/src/id_type/api_key.rs b/crates/common_utils/src/id_type/api_key.rs
new file mode 100644
index 00000000000..f252846e6ac
--- /dev/null
+++ b/crates/common_utils/src/id_type/api_key.rs
@@ -0,0 +1,46 @@
+crate::id_type!(
+ ApiKeyId,
+ "A type for key_id that can be used for API key IDs"
+);
+crate::impl_id_type_methods!(ApiKeyId, "key_id");
+
+// This is to display the `ApiKeyId` as ApiKeyId(abcd)
+crate::impl_debug_id_type!(ApiKeyId);
+crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id");
+
+crate::impl_serializable_secret_id_type!(ApiKeyId);
+crate::impl_queryable_id_type!(ApiKeyId);
+crate::impl_to_sql_from_sql_id_type!(ApiKeyId);
+
+impl ApiKeyId {
+ /// Generate Api Key Id from prefix
+ pub fn generate_key_id(prefix: &'static str) -> Self {
+ Self(crate::generate_ref_id_with_default_length(prefix))
+ }
+}
+
+impl crate::events::ApiEventMetric for ApiKeyId {
+ fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
+ Some(crate::events::ApiEventsType::ApiKey {
+ key_id: self.clone(),
+ })
+ }
+}
+
+impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) {
+ fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
+ Some(crate::events::ApiEventsType::ApiKey {
+ key_id: self.1.clone(),
+ })
+ }
+}
+
+impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) {
+ fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
+ Some(crate::events::ApiEventsType::ApiKey {
+ key_id: self.1.clone(),
+ })
+ }
+}
+
+crate::impl_default_id_type!(ApiKeyId, "key");
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs
index 1781e65cded..7076bf597e0 100644
--- a/crates/diesel_models/src/api_keys.rs
+++ b/crates/diesel_models/src/api_keys.rs
@@ -9,7 +9,7 @@ use crate::schema::api_keys;
)]
#[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))]
pub struct ApiKey {
- pub key_id: String,
+ pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
@@ -23,7 +23,7 @@ pub struct ApiKey {
#[derive(Debug, Insertable)]
#[diesel(table_name = api_keys)]
pub struct ApiKeyNew {
- pub key_id: String,
+ pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
@@ -141,7 +141,7 @@ mod diesel_impl {
// Tracking data by process_tracker
#[derive(Default, Debug, Deserialize, Serialize, Clone)]
pub struct ApiKeyExpiryTrackingData {
- pub key_id: String,
+ pub key_id: common_utils::id_type::ApiKeyId,
pub merchant_id: common_utils::id_type::MerchantId,
pub api_key_name: String,
pub prefix: String,
diff --git a/crates/diesel_models/src/query/api_keys.rs b/crates/diesel_models/src/query/api_keys.rs
index 5dd14501025..479e226c1d3 100644
--- a/crates/diesel_models/src/query/api_keys.rs
+++ b/crates/diesel_models/src/query/api_keys.rs
@@ -18,7 +18,7 @@ impl ApiKey {
pub async fn update_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
api_key_update: ApiKeyUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
@@ -57,7 +57,7 @@ impl ApiKey {
pub async fn revoke_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
@@ -71,7 +71,7 @@ impl ApiKey {
pub async fn find_optional_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 6e907dbd91b..de4a8931c78 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -13,7 +13,6 @@ use crate::{
routes::{metrics, SessionState},
services::{authentication, ApplicationResponse},
types::{api, storage, transformers::ForeignInto},
- utils,
};
#[cfg(feature = "email")]
@@ -63,9 +62,9 @@ impl PlaintextApiKey {
Self(format!("{env}_{key}").into())
}
- pub fn new_key_id() -> String {
+ pub fn new_key_id() -> common_utils::id_type::ApiKeyId {
let env = router_env::env::prefix_for_env();
- utils::generate_id(consts::ID_LENGTH, env)
+ common_utils::id_type::ApiKeyId::generate_key_id(env)
}
pub fn prefix(&self) -> String {
@@ -223,7 +222,7 @@ pub async fn add_api_key_expiry_task(
expiry_reminder_days: expiry_reminder_days.clone(),
};
- let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str());
+ let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
API_KEY_EXPIRY_NAME,
@@ -241,7 +240,7 @@ pub async fn add_api_key_expiry_task(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
- "Failed while inserting API key expiry reminder to process_tracker: api_key_id: {}",
+ "Failed while inserting API key expiry reminder to process_tracker: {:?}",
api_key.key_id
)
})?;
@@ -258,11 +257,11 @@ pub async fn add_api_key_expiry_task(
pub async fn retrieve_api_key(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
- .find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id)
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
@@ -388,7 +387,7 @@ pub async fn update_api_key_expiry_task(
}
}
- let task_id = generate_task_id_for_api_key_expiry_workflow(api_key.key_id.as_str());
+ let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let task_ids = vec![task_id.clone()];
@@ -430,7 +429,7 @@ pub async fn update_api_key_expiry_task(
pub async fn revoke_api_key(
state: SessionState,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RevokeApiKeyResponse> {
let store = state.store.as_ref();
@@ -496,7 +495,7 @@ pub async fn revoke_api_key(
#[instrument(skip_all)]
pub async fn revoke_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> Result<(), errors::ProcessTrackerError> {
let task_id = generate_task_id_for_api_key_expiry_workflow(key_id);
let task_ids = vec![task_id];
@@ -535,8 +534,13 @@ pub async fn list_api_keys(
}
#[cfg(feature = "email")]
-fn generate_task_id_for_api_key_expiry_workflow(key_id: &str) -> String {
- format!("{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{key_id}")
+fn generate_task_id_for_api_key_expiry_workflow(
+ key_id: &common_utils::id_type::ApiKeyId,
+) -> String {
+ format!(
+ "{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}",
+ key_id.get_string_repr()
+ )
}
impl From<&str> for PlaintextApiKey {
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs
index 62d261aa3c4..0d3ec5dc8c2 100644
--- a/crates/router/src/db/api_keys.rs
+++ b/crates/router/src/db/api_keys.rs
@@ -20,20 +20,20 @@ pub trait ApiKeyInterface {
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError>;
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError>;
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
async fn find_api_key_by_hash_optional(
@@ -67,7 +67,7 @@ impl ApiKeyInterface for Store {
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -99,7 +99,8 @@ impl ApiKeyInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.ok_or(report!(errors::StorageError::ValueNotFound(format!(
- "ApiKey of {_key_id} not found"
+ "ApiKey of {} not found",
+ _key_id.get_string_repr()
))))?;
cache::publish_and_redact(
@@ -115,7 +116,7 @@ impl ApiKeyInterface for Store {
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let delete_call = || async {
@@ -141,7 +142,8 @@ impl ApiKeyInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.ok_or(report!(errors::StorageError::ValueNotFound(format!(
- "ApiKey of {key_id} not found"
+ "ApiKey of {} not found",
+ key_id.get_string_repr()
))))?;
cache::publish_and_redact(
@@ -157,7 +159,7 @@ impl ApiKeyInterface for Store {
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id)
@@ -240,7 +242,7 @@ impl ApiKeyInterface for MockDb {
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
@@ -282,13 +284,13 @@ impl ApiKeyInterface for MockDb {
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
// find the key to remove, if it exists
if let Some(pos) = locked_api_keys
.iter()
- .position(|k| k.merchant_id == *merchant_id && k.key_id == key_id)
+ .position(|k| k.merchant_id == *merchant_id && k.key_id == *key_id)
{
// use `remove` instead of `swap_remove` so we have a consistent order, which might
// matter to someone using limit/offset in `list_api_keys_by_merchant_id`
@@ -302,14 +304,14 @@ impl ApiKeyInterface for MockDb {
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- key_id: &str,
+ key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
Ok(self
.api_keys
.lock()
.await
.iter()
- .find(|k| k.merchant_id == *merchant_id && k.key_id == key_id)
+ .find(|k| k.merchant_id == *merchant_id && k.key_id == *key_id)
.cloned())
}
@@ -397,9 +399,16 @@ mod tests {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap();
+ let key_id1 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id1")).unwrap();
+
+ let key_id2 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id2")).unwrap();
+
+ let non_existent_key_id =
+ common_utils::id_type::ApiKeyId::try_from(Cow::from("does_not_exist")).unwrap();
+
let key1 = mockdb
.insert_api_key(storage::ApiKeyNew {
- key_id: "key_id1".into(),
+ key_id: key_id1.clone(),
merchant_id: merchant_id.clone(),
name: "Key 1".into(),
description: None,
@@ -414,7 +423,7 @@ mod tests {
mockdb
.insert_api_key(storage::ApiKeyNew {
- key_id: "key_id2".into(),
+ key_id: key_id2.clone(),
merchant_id: merchant_id.clone(),
name: "Key 2".into(),
description: None,
@@ -428,13 +437,13 @@ mod tests {
.unwrap();
let found_key1 = mockdb
- .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1)
.await
.unwrap()
.unwrap();
assert_eq!(found_key1.key_id, key1.key_id);
assert!(mockdb
- .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "does_not_exist")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &non_existent_key_id)
.await
.unwrap()
.is_none());
@@ -442,7 +451,7 @@ mod tests {
mockdb
.update_api_key(
merchant_id.clone(),
- "key_id1".into(),
+ key_id1.clone(),
storage::ApiKeyUpdate::LastUsedUpdate {
last_used: datetime!(2023-02-04 1:11),
},
@@ -450,7 +459,7 @@ mod tests {
.await
.unwrap();
let updated_key1 = mockdb
- .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1)
.await
.unwrap()
.unwrap();
@@ -464,10 +473,7 @@ mod tests {
.len(),
2
);
- mockdb
- .revoke_api_key(&merchant_id, "key_id1")
- .await
- .unwrap();
+ mockdb.revoke_api_key(&merchant_id, &key_id1).await.unwrap();
assert_eq!(
mockdb
.list_api_keys_by_merchant_id(&merchant_id, None, None)
@@ -495,8 +501,10 @@ mod tests {
.await
.unwrap();
+ let test_key = common_utils::id_type::ApiKeyId::try_from(Cow::from("test_ey")).unwrap();
+
let api = storage::ApiKeyNew {
- key_id: "test_key".into(),
+ key_id: test_key.clone(),
merchant_id: merchant_id.clone(),
name: "My test key".into(),
description: None,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 6e9daeedc59..208cd8d5f97 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -226,7 +226,7 @@ impl ApiKeyInterface for KafkaStore {
async fn update_api_key(
&self,
merchant_id: id_type::MerchantId,
- key_id: String,
+ key_id: id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
self.diesel_store
@@ -237,7 +237,7 @@ impl ApiKeyInterface for KafkaStore {
async fn revoke_api_key(
&self,
merchant_id: &id_type::MerchantId,
- key_id: &str,
+ key_id: &id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store.revoke_api_key(merchant_id, key_id).await
}
@@ -245,7 +245,7 @@ impl ApiKeyInterface for KafkaStore {
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &id_type::MerchantId,
- key_id: &str,
+ key_id: &id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id)
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index 047e0d9b886..bbecaae9e80 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -79,7 +79,7 @@ pub async fn api_key_create(
pub async fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::ApiKeyId>,
) -> impl Responder {
let flow = Flow::ApiKeyRetrieve;
let key_id = path.into_inner();
@@ -93,7 +93,7 @@ pub async fn api_key_retrieve(
api_keys::retrieve_api_key(
state,
auth_data.merchant_account.get_id().to_owned(),
- key_id,
+ key_id.to_owned(),
)
},
auth::auth_type(
@@ -114,7 +114,10 @@ pub async fn api_key_retrieve(
pub async fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(common_utils::id_type::MerchantId, String)>,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ApiKeyId,
+ )>,
) -> impl Responder {
let flow = Flow::ApiKeyRetrieve;
let (merchant_id, key_id) = path.into_inner();
@@ -123,7 +126,7 @@ pub async fn api_key_retrieve(
flow,
state,
&req,
- (merchant_id.clone(), &key_id),
+ (merchant_id.clone(), key_id.clone()),
|state, _, (merchant_id, key_id), _| api_keys::retrieve_api_key(state, merchant_id, key_id),
auth::auth_type(
&auth::AdminApiAuth,
@@ -144,7 +147,10 @@ pub async fn api_key_retrieve(
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(common_utils::id_type::MerchantId, String)>,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ApiKeyId,
+ )>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
@@ -177,7 +183,7 @@ pub async fn api_key_update(
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
- key_id: web::Path<String>,
+ key_id: web::Path<common_utils::id_type::ApiKeyId>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
@@ -212,7 +218,10 @@ pub async fn api_key_update(
pub async fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(common_utils::id_type::MerchantId, String)>,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ApiKeyId,
+ )>,
) -> impl Responder {
let flow = Flow::ApiKeyRevoke;
let (merchant_id, key_id) = path.into_inner();
@@ -242,7 +251,10 @@ pub async fn api_key_revoke(
pub async fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(common_utils::id_type::MerchantId, String)>,
+ path: web::Path<(
+ common_utils::id_type::MerchantId,
+ common_utils::id_type::ApiKeyId,
+ )>,
) -> impl Responder {
let flow = Flow::ApiKeyRevoke;
let (merchant_id, key_id) = path.into_inner();
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 3731d8ee081..9be4c493874 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -82,7 +82,7 @@ pub struct AuthenticationDataWithUser {
pub enum AuthenticationType {
ApiKey {
merchant_id: id_type::MerchantId,
- key_id: String,
+ key_id: id_type::ApiKeyId,
},
AdminApiKey,
AdminApiAuthWithMerchantId {
diff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rs
index d665b0caaf4..c31a4696bc9 100644
--- a/crates/router/src/services/authentication/decision.rs
+++ b/crates/router/src/services/authentication/decision.rs
@@ -67,7 +67,7 @@ pub enum Identifiers {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
ApiKey {
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
},
/// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`]
PublishableKey { merchant_id: String },
@@ -80,7 +80,7 @@ pub async fn add_api_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
- key_id: String,
+ key_id: common_utils::id_type::ApiKeyId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
diff --git a/crates/router/src/services/authentication/detached.rs b/crates/router/src/services/authentication/detached.rs
index af373d3e559..9d77d2b1f07 100644
--- a/crates/router/src/services/authentication/detached.rs
+++ b/crates/router/src/services/authentication/detached.rs
@@ -1,7 +1,10 @@
use std::{borrow::Cow, string::ToString};
use actix_web::http::header::HeaderMap;
-use common_utils::{crypto::VerifySignature, id_type::MerchantId};
+use common_utils::{
+ crypto::VerifySignature,
+ id_type::{ApiKeyId, MerchantId},
+};
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
@@ -16,7 +19,7 @@ const HEADER_CHECKSUM: &str = "x-checksum";
pub struct ExtractedPayload {
pub payload_type: PayloadType,
pub merchant_id: Option<MerchantId>,
- pub key_id: Option<String>,
+ pub key_id: Option<ApiKeyId>,
}
#[derive(strum::EnumString, strum::Display, PartialEq, Debug)]
@@ -61,13 +64,19 @@ impl ExtractedPayload {
message: format!("`{}` header not present", HEADER_AUTH_TYPE),
})?;
+ let key_id = headers
+ .get(HEADER_KEY_ID)
+ .and_then(|value| value.to_str().ok())
+ .map(|key_id| ApiKeyId::try_from(Cow::from(key_id.to_string())))
+ .transpose()
+ .change_context(ApiErrorResponse::InvalidRequestData {
+ message: format!("`{}` header is invalid or not present", HEADER_KEY_ID),
+ })?;
+
Ok(Self {
payload_type: auth_type,
merchant_id: Some(merchant_id),
- key_id: headers
- .get(HEADER_KEY_ID)
- .and_then(|v| v.to_str().ok())
- .map(|v| v.to_string()),
+ key_id,
})
}
@@ -95,7 +104,7 @@ impl ExtractedPayload {
&self
.merchant_id
.as_ref()
- .map(|inner| append_option(inner.get_string_repr(), &self.key_id)),
+ .map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)),
)
}
}
@@ -107,3 +116,11 @@ fn append_option(prefix: &str, data: &Option<String>) -> String {
None => prefix.to_string(),
}
}
+
+#[inline]
+fn append_api_key(prefix: &str, data: &Option<ApiKeyId>) -> String {
+ match data {
+ Some(inner) => format!("{}:{}", prefix, inner.get_string_repr()),
+ None => prefix.to_string(),
+ }
+}
|
2024-10-15T12:16:41Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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. Create API key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729063721' \
--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"
}'
```
1b. Response
```json
{
"key_id": "dev_ZfucbDHJm7pbcFjsoq5I",
"merchant_id": "merchant_1729063721",
"name": "API Key 1",
"description": null,
"api_key": "dev_sNyAhsbOkEYtuuUvMOzlTIMpTZ3Kd9AC5sboxRuQOMX5xKyqTDn0oG9Vaq4XGwN1",
"created": "2024-10-16T07:28:44.906Z",
"expiration": "2038-01-19T03:14:08.000Z"
}
```
2a. Update API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"name": null,
"description": "My very awesome API key",
"expiration": null
}'
```
2b. Reponse
```json
{
"key_id": "dev_ZfucbDHJm7pbcFjsoq5I",
"merchant_id": "merchant_1729063721",
"name": "API Key 1",
"description": "My very awesome API key",
"prefix": "dev_sNyAhsbO",
"created": "2024-10-16T07:28:44.906Z",
"expiration": "2038-01-19T03:14:08.000Z"
}
```
3a. Retrieve API Key
```
curl --location 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin'
```
3b. Response
```json
{
"key_id": "dev_ZfucbDHJm7pbcFjsoq5I",
"merchant_id": "merchant_1729063721",
"name": "API Key 1",
"description": "My very awesome API key",
"prefix": "dev_sNyAhsbO",
"created": "2024-10-16T07:28:44.906Z",
"expiration": "2038-01-19T03:14:08.000Z"
}
```
4a. Delete API Key
```
curl --location --request DELETE 'http://localhost:8080/api_keys/merchant_1729063721/dev_ZfucbDHJm7pbcFjsoq5I' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin'
```
4b. Response
```json
{
"merchant_id": "merchant_1729063721",
"key_id": "dev_ZfucbDHJm7pbcFjsoq5I",
"revoked": true
}
```
5a. List API Keys
```
curl --location 'http://localhost:8080/api_keys/merchant_1729063721/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin'
```
5b. Response
```json
[
{
"key_id": "dev_kKu6dWq8k3ZwWOfsS3fi",
"merchant_id": "merchant_1729063721",
"name": "API Key 1",
"description": null,
"prefix": "dev_6gvWcG7g",
"created": "2024-10-16T07:32:48.698Z",
"expiration": "2038-01-19T03:14:08.000Z"
},
{
"key_id": "dev_f1PMFHmWHi2v0fmZp7t2",
"merchant_id": "merchant_1729063721",
"name": "API Key 2",
"description": null,
"prefix": "dev_jSU9qvIU",
"created": "2024-10-16T07:32:54.057Z",
"expiration": "2038-01-19T03:14:08.000Z"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
899ec23565f99daaad821c1ec1482b4c0cc408c5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6321
|
Bug: [BUG] Various errors in `rust_locker_open_api_spec.yml`
### Bug Description
The two identical files [`api-reference/rust_locker_open_api_spec.yml`](https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml) and [`api-reference-v2/rust_locker_open_api_spec.yml`](https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference-v2/rust_locker_open_api_spec.yml) contain some mistakes and errors.
### Expected Behavior
The documentation should be clear.
### Actual Behavior
The documentation contains some errors.
### Steps To Reproduce
Not relevant.
### Context For The Bug
Some examples:
https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L5
https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L12
https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L14
https://github.com/juspay/hyperswitch/blob/d06d19fc96e1a74d20e2fe3613f86d541947e0ae/api-reference/rust_locker_open_api_spec.yml#L42
### 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/api-reference-v2/rust_locker_open_api_spec.yml b/api-reference-v2/rust_locker_open_api_spec.yml
index 729886d9cd0..17a19fec44d 100644
--- a/api-reference-v2/rust_locker_open_api_spec.yml
+++ b/api-reference-v2/rust_locker_open_api_spec.yml
@@ -2,16 +2,16 @@ openapi: "3.0.2"
info:
title: Tartarus - OpenAPI 3.0
description: |-
- This the the open API 3.0 specification for the card locker.
+ This is the OpenAPI 3.0 specification for the card locker.
This is used by the [hyperswitch](https://github.com/juspay/hyperswitch) for storing card information securely.
version: "1.0"
tags:
- name: Key Custodian
description: API used to initialize the locker after deployment.
- name: Data
- description: CRUD APIs to for working with data to be stored in the locker
+ description: CRUD APIs for working with data to be stored in the locker
- name: Cards
- description: CRUD APIs to for working with cards data to be stored in the locker (deprecated)
+ description: CRUD APIs for working with cards data to be stored in the locker (deprecated)
paths:
/custodian/key1:
post:
@@ -39,7 +39,7 @@ paths:
tags:
- Key Custodian
summary: Provide Key 2
- description: Provide the first key to unlock the locker
+ description: Provide the second key to unlock the locker
operationId: setKey2
requestBody:
description: Provide key 2 to unlock the locker
|
2024-10-15T10:54:46Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Improved wording in the edit files.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 #6321.
## How did you test 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 inspected the changed files.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e5710fa084ed5b0a4969a63b14a7f8e3433a3c64
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6338
|
Bug: Integration of dynamic connector selection in core flows
## Description
This will integrate the dynamic_connector_selection in core flows, enabling the success_based connector selection for payments (with the profiles, enabled with dynamic_connector_selection feature).
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index fc65ab037c2..47d75b2e835 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -522,22 +522,51 @@ pub struct DynamicAlgorithmWithTimestamp<T> {
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
- pub success_based_algorithm:
- Option<DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>>,
+ pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct SuccessBasedAlgorithm {
+ pub algorithm_id_with_timestamp:
+ DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
+ #[serde(default)]
+ pub enabled_feature: SuccessBasedRoutingFeatures,
+}
+
+impl SuccessBasedAlgorithm {
+ pub fn update_enabled_features(&mut self, feature_to_enable: SuccessBasedRoutingFeatures) {
+ self.enabled_feature = feature_to_enable
+ }
}
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(),
+ pub fn update_algorithm_id(
+ &mut self,
+ new_id: common_utils::id_type::RoutingId,
+ enabled_feature: SuccessBasedRoutingFeatures,
+ ) {
+ self.success_based_algorithm = Some(SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(new_id),
+ timestamp: common_utils::date_time::now_unix_timestamp(),
+ },
+ enabled_feature,
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleSuccessBasedRoutingQuery {
- pub status: bool,
+ pub enable: SuccessBasedRoutingFeatures,
+}
+
+#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum SuccessBasedRoutingFeatures {
+ Metrics,
+ DynamicConnectorSelection,
+ #[default]
+ None,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -551,7 +580,7 @@ pub struct SuccessBasedRoutingUpdateConfigQuery {
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ToggleSuccessBasedRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
- pub status: bool,
+ pub feature_to_enable: SuccessBasedRoutingFeatures,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index a76726eb8ac..b459cee7ad4 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -159,7 +159,6 @@ Never share your secret api keys. Keep them guarded and secure.
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,
@@ -559,6 +558,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
+ api_models::routing::SuccessBasedRoutingFeatures,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
@@ -570,11 +570,6 @@ Never share your secret api keys. Keep them guarded and secure.
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,
diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs
index 009708d860d..0bb79a2bbe4 100644
--- a/crates/openapi/src/routes/routing.rs
+++ b/crates/openapi/src/routes/routing.rs
@@ -266,7 +266,7 @@ pub async fn routing_update_default_config_for_profile() {}
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"),
+ ("enable" = SuccessBasedRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
@@ -281,30 +281,3 @@ pub async fn routing_update_default_config_for_profile() {}
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/errors.rs b/crates/router/src/core/errors.rs
index c56bfaca913..18af1b064cd 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -318,6 +318,20 @@ pub enum RoutingError {
VolumeSplitFailed,
#[error("Unable to parse metadata")]
MetadataParsingError,
+ #[error("Unable to retrieve success based routing config")]
+ SuccessBasedRoutingConfigError,
+ #[error("Unable to calculate success based routing config from dynamic routing service")]
+ SuccessRateCalculationError,
+ #[error("Success rate client from dynamic routing gRPC service not initialized")]
+ SuccessRateClientInitializationError,
+ #[error("Unable to convert from '{from}' to '{to}'")]
+ GenericConversionError { from: String, to: String },
+ #[error("Invalid success based connector label received from dynamic routing service: '{0}'")]
+ InvalidSuccessBasedConnectorLabel(String),
+ #[error("unable to find '{field}'")]
+ GenericNotFoundError { field: String },
+ #[error("Unable to deserialize from '{from}' to '{to}'")]
+ DeserializationError { from: String, to: String },
}
#[derive(Debug, Clone, thiserror::Error)]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 9f904116171..568fcb20902 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4591,6 +4591,19 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
+ // dynamic success based connector selection
+ #[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+ let connectors = {
+ if business_profile.dynamic_routing_algorithm.is_some() {
+ routing::perform_success_based_routing(state, connectors.clone(), business_profile)
+ .await
+ .map_err(|e| logger::error!(success_rate_routing_error=?e))
+ .unwrap_or(connectors)
+ } else {
+ connectors
+ }
+ };
+
let connector_data = connectors
.into_iter()
.map(|conn| {
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6a5299db8c4..8a6fad6a60a 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1713,8 +1713,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
{
- if let Some(dynamic_routing_algorithm) = business_profile.dynamic_routing_algorithm.clone()
- {
+ if business_profile.dynamic_routing_algorithm.is_some() {
let state = state.clone();
let business_profile = business_profile.clone();
let payment_attempt = payment_attempt.clone();
@@ -1725,7 +1724,6 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
&payment_attempt,
routable_connectors,
&business_profile,
- dynamic_routing_algorithm,
)
.await
.map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 04080a42730..dbb08e770a1 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -7,6 +7,8 @@ use std::{
sync::Arc,
};
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
@@ -21,6 +23,10 @@ use euclid::{
enums as euclid_enums,
frontend::{ast, dir as euclid_dir},
};
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+use external_services::grpc_client::dynamic_routing::{
+ success_rate::CalSuccessRateResponse, SuccessBasedDynamicRouting,
+};
use kgraph_utils::{
mca as mca_graph,
transformers::{IntoContext, IntoDirValue},
@@ -1202,3 +1208,114 @@ pub fn make_dsl_input_for_surcharge(
};
Ok(backend_input)
}
+
+/// success based dynamic routing
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn perform_success_based_routing(
+ state: &SessionState,
+ routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
+ business_profile: &domain::Profile,
+) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
+ let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef =
+ business_profile
+ .dynamic_routing_algorithm
+ .clone()
+ .map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
+ .transpose()
+ .change_context(errors::RoutingError::DeserializationError {
+ from: "JSON".to_string(),
+ to: "DynamicRoutingAlgorithmRef".to_string(),
+ })
+ .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
+ .unwrap_or_default();
+
+ let success_based_algo_ref = success_based_dynamic_routing_algo_ref
+ .success_based_algorithm
+ .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_algorithm".to_string() })
+ .attach_printable(
+ "success_based_algorithm not found in dynamic_routing_algorithm from business_profile table",
+ )?;
+
+ if success_based_algo_ref.enabled_feature
+ == api_routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection
+ {
+ logger::debug!(
+ "performing success_based_routing for profile {}",
+ business_profile.get_id().get_string_repr()
+ );
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .success_rate_client
+ .as_ref()
+ .ok_or(errors::RoutingError::SuccessRateClientInitializationError)
+ .attach_printable("success_rate gRPC client not found")?;
+
+ let success_based_routing_configs = routing::helpers::fetch_success_based_routing_configs(
+ state,
+ business_profile,
+ success_based_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::RoutingError::GenericNotFoundError {
+ field: "success_based_routing_algorithm_id".to_string(),
+ })
+ .attach_printable(
+ "success_based_routing_algorithm_id not found in business_profile",
+ )?,
+ )
+ .await
+ .change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
+ .attach_printable("unable to fetch success_rate based dynamic routing configs")?;
+
+ let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(
+ &state.tenant.redis_key_prefix,
+ business_profile.get_id().get_string_repr(),
+ );
+
+ let success_based_connectors: CalSuccessRateResponse = client
+ .calculate_success_rate(
+ tenant_business_profile_id,
+ success_based_routing_configs,
+ routable_connectors,
+ )
+ .await
+ .change_context(errors::RoutingError::SuccessRateCalculationError)
+ .attach_printable(
+ "unable to calculate/fetch success rate from dynamic routing service",
+ )?;
+
+ let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len());
+ for label_with_score in success_based_connectors.labels_with_score {
+ let (connector, merchant_connector_id) = label_with_score.label
+ .split_once(':')
+ .ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string()))
+ .attach_printable(
+ "unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
+ )?;
+ connectors.push(api_routing::RoutableConnectorChoice {
+ choice_kind: api_routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(connector)
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "RoutableConnectors".to_string(),
+ })
+ .attach_printable("unable to convert String to RoutableConnectors")?,
+ merchant_connector_id: Some(
+ common_utils::id_type::MerchantConnectorAccountId::wrap(
+ merchant_connector_id.to_string(),
+ )
+ .change_context(errors::RoutingError::GenericConversionError {
+ from: "String".to_string(),
+ to: "MerchantConnectorAccountId".to_string(),
+ })
+ .attach_printable("unable to convert MerchantConnectorAccountId from string")?,
+ ),
+ });
+ }
+ logger::debug!(success_based_routing_connectors=?connectors);
+ Ok(connectors)
+ } else {
+ Ok(routable_connectors)
+ }
+}
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index b7b1c13ea80..35c4b8d9621 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -434,9 +434,13 @@ pub async fn link_routing_config(
utils::when(
matches!(
dynamic_routing_ref.success_based_algorithm,
- Some(routing_types::DynamicAlgorithmWithTimestamp {
- algorithm_id: Some(ref id),
- timestamp: _
+ Some(routing::SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: Some(ref id),
+ timestamp: _
+ },
+ enabled_feature: _
}) if id == &algorithm_id
),
|| {
@@ -446,7 +450,17 @@ pub async fn link_routing_config(
},
)?;
- dynamic_routing_ref.update_algorithm_id(algorithm_id);
+ dynamic_routing_ref.update_algorithm_id(
+ algorithm_id,
+ dynamic_routing_ref
+ .success_based_algorithm
+ .clone()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "missing success_based_algorithm in dynamic_algorithm_ref from business_profile table",
+ )?
+ .enabled_feature,
+ );
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
@@ -1162,7 +1176,7 @@ pub async fn toggle_success_based_routing(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- status: bool,
+ feature_to_enable: routing::SuccessBasedRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
@@ -1198,115 +1212,158 @@ pub async fn toggle_success_based_routing(
)?
.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,
- },
- ),
- };
-
- // redact cache for success based routing configs
- let cache_key = format!(
- "{}_{}",
- business_profile.get_id().get_string_repr(),
- algorithm_id.get_string_repr()
- );
- let cache_entries_to_redact =
- vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
- cache_key.into(),
- )];
- let _ = cache::publish_into_redact_channel(
- state.store.get_cache_store().as_ref(),
- cache_entries_to_redact,
- )
- .await
- .map_err(|e| {
- logger::error!(
- "unable to publish into the redact channel for evicting the success based routing config cache {e:?}"
+ match feature_to_enable {
+ routing::SuccessBasedRoutingFeatures::Metrics
+ | routing::SuccessBasedRoutingFeatures::DynamicConnectorSelection => {
+ if let Some(ref mut algo_with_timestamp) =
+ success_based_dynamic_routing_algo_ref.success_based_algorithm
+ {
+ match algo_with_timestamp
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .clone()
+ {
+ Some(algorithm_id) => {
+ // algorithm is already present in profile
+ if algo_with_timestamp.enabled_feature == feature_to_enable {
+ // algorithm already has the required feature
+ Err(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Success rate based routing is already enabled"
+ .to_string(),
+ })?
+ } else {
+ // enable the requested feature for the algorithm
+ algo_with_timestamp.update_enabled_features(feature_to_enable);
+ 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,
+ success_based_dynamic_routing_algo_ref,
+ )
+ .await?;
+
+ 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(response))
+ }
+ }
+ None => {
+ // algorithm isn't present in profile
+ helpers::default_success_based_routing_setup(
+ &state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ merchant_account.get_id().to_owned(),
+ success_based_dynamic_routing_algo_ref,
)
- });
+ .await
+ }
+ }
+ } else {
+ // algorithm isn't present in profile
+ helpers::default_success_based_routing_setup(
+ &state,
+ key_store,
+ business_profile,
+ feature_to_enable,
+ merchant_account.get_id().to_owned(),
+ success_based_dynamic_routing_algo_ref,
+ )
+ .await
+ }
+ }
+ routing::SuccessBasedRoutingFeatures::None => {
+ // disable success based routing for the requested profile
+ 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_with_timestamp.algorithm_id
+ {
+ let dynamic_routing_algorithm = routing_types::DynamicRoutingAlgorithmRef {
+ success_based_algorithm: Some(routing::SuccessBasedAlgorithm {
+ algorithm_id_with_timestamp:
+ routing_types::DynamicAlgorithmWithTimestamp {
+ algorithm_id: None,
+ timestamp,
+ },
+ enabled_feature: routing::SuccessBasedRoutingFeatures::None,
+ }),
+ };
- let record = db
- .find_routing_algorithm_by_profile_id_algorithm_id(
- business_profile.get_id(),
- &algorithm_id,
+ // redact cache for success based routing configs
+ let cache_key = format!(
+ "{}_{}",
+ business_profile.get_id().get_string_repr(),
+ algorithm_id.get_string_repr()
+ );
+ let cache_entries_to_redact =
+ vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
+ cache_key.into(),
+ )];
+ let _ = cache::publish_into_redact_channel(
+ state.store.get_cache_store().as_ref(),
+ cache_entries_to_redact,
)
.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(),
- })?
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to publish into the redact channel for evicting the success based routing config cache")?;
+
+ 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: "Success rate based routing is already disabled".to_string(),
+ })?,
}
- None => Err(errors::ApiErrorResponse::PreconditionFailed {
- message: "Algorithm is already inactive".to_string(),
- })?,
}
}
}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 22966208dd4..6b584583174 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -12,10 +12,16 @@ use api_models::routing as routing_types;
use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState};
use diesel_models::configs;
+#[cfg(feature = "v1")]
+use diesel_models::routing_algorithm;
use error_stack::ResultExt;
-#[cfg(feature = "dynamic_routing")]
+#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use external_services::grpc_client::dynamic_routing::SuccessBasedDynamicRouting;
+#[cfg(feature = "v1")]
+use hyperswitch_domain_models::api::ApplicationResponse;
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
+use router_env::logger;
+#[cfg(any(feature = "dynamic_routing", feature = "v1"))]
use router_env::{instrument, metrics::add_attributes, tracing};
use rustc_hash::FxHashSet;
use storage_impl::redis::cache;
@@ -29,8 +35,10 @@ use crate::{
types::{domain, storage},
utils::StringExt,
};
-#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
-use crate::{core::metrics as core_metrics, routes::metrics};
+#[cfg(feature = "v1")]
+use crate::{core::metrics as core_metrics, routes::metrics, types::transformers::ForeignInto};
+pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str =
+ "Success rate based dynamic routing algorithm";
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
@@ -594,28 +602,8 @@ pub async fn refresh_success_based_routing_cache(
pub async fn fetch_success_based_routing_configs(
state: &SessionState,
business_profile: &domain::Profile,
- dynamic_routing_algorithm: serde_json::Value,
+ success_based_routing_id: id_type::RoutingId,
) -> RouterResult<routing_types::SuccessBasedRoutingConfig> {
- let dynamic_routing_algorithm_ref = dynamic_routing_algorithm
- .parse_value::<routing_types::DynamicRoutingAlgorithmRef>("DynamicRoutingAlgorithmRef")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to parse dynamic_routing_algorithm_ref")?;
-
- let success_based_routing_id = dynamic_routing_algorithm_ref
- .success_based_algorithm
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: "success_based_algorithm not found in dynamic_routing_algorithm_ref"
- .to_string(),
- })?
- .algorithm_id
- // error can be possible when the feature is toggled off.
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: format!(
- "unable to find algorithm_id in success based algorithm config as the feature is disabled for profile_id: {}",
- business_profile.get_id().get_string_repr()
- ),
- })?;
-
let key = format!(
"{}_{}",
business_profile.get_id().get_string_repr(),
@@ -657,156 +645,185 @@ pub async fn push_metrics_for_success_based_routing(
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
business_profile: &domain::Profile,
- dynamic_routing_algorithm: serde_json::Value,
) -> RouterResult<()> {
- let client = state
- .grpc_client
- .dynamic_routing
- .success_rate_client
- .as_ref()
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: "success_rate gRPC client not found".to_string(),
- })?;
-
- let payment_connector = &payment_attempt.connector.clone().ok_or(
- errors::ApiErrorResponse::GenericNotFoundError {
- message: "unable to derive payment connector from payment attempt".to_string(),
- },
- )?;
-
- let success_based_routing_configs =
- fetch_success_based_routing_configs(state, business_profile, dynamic_routing_algorithm)
- .await
+ let 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 retrieve success_rate based dynamic routing configs")?;
+ .attach_printable("Failed to deserialize DynamicRoutingAlgorithmRef from JSON")?
+ .unwrap_or_default();
- let tenant_business_profile_id = format!(
- "{}:{}",
- state.tenant.redis_key_prefix,
- business_profile.get_id().get_string_repr()
- );
+ let success_based_algo_ref = success_based_dynamic_routing_algo_ref
+ .success_based_algorithm
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?;
+
+ if success_based_algo_ref.enabled_feature != routing_types::SuccessBasedRoutingFeatures::None {
+ let client = state
+ .grpc_client
+ .dynamic_routing
+ .success_rate_client
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "success_rate gRPC client not found".to_string(),
+ })?;
+
+ let payment_connector = &payment_attempt.connector.clone().ok_or(
+ errors::ApiErrorResponse::GenericNotFoundError {
+ message: "unable to derive payment connector from payment attempt".to_string(),
+ },
+ )?;
- let success_based_connectors = client
- .calculate_success_rate(
- tenant_business_profile_id.clone(),
- success_based_routing_configs.clone(),
- routable_connectors.clone(),
+ let success_based_routing_configs = fetch_success_based_routing_configs(
+ state,
+ business_profile,
+ success_based_algo_ref
+ .algorithm_id_with_timestamp
+ .algorithm_id
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "success_based_routing_algorithm_id not found in business_profile",
+ )?,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to calculate/fetch success rate from dynamic routing service")?;
-
- let payment_status_attribute =
- get_desired_payment_status_for_success_routing_metrics(&payment_attempt.status);
-
- let first_success_based_connector_label = &success_based_connectors
- .labels_with_score
- .first()
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
- )?
- .label
- .to_string();
-
- let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label
- .split_once(':')
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service",
- )?;
-
- let outcome = get_success_based_metrics_outcome_for_payment(
- &payment_status_attribute,
- payment_connector.to_string(),
- first_success_based_connector.to_string(),
- );
-
- core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
- &metrics::CONTEXT,
- 1,
- &add_attributes([
- ("tenant", state.tenant.name.clone()),
- (
- "merchant_id",
- payment_attempt.merchant_id.get_string_repr().to_string(),
- ),
- (
- "profile_id",
- payment_attempt.profile_id.get_string_repr().to_string(),
- ),
- ("merchant_connector_id", merchant_connector_id.to_string()),
- (
- "payment_id",
- payment_attempt.payment_id.get_string_repr().to_string(),
- ),
- (
- "success_based_routing_connector",
- first_success_based_connector.to_string(),
- ),
- ("payment_connector", payment_connector.to_string()),
- (
- "currency",
- payment_attempt
- .currency
- .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
- ),
- (
- "payment_method",
- payment_attempt.payment_method.map_or_else(
- || "None".to_string(),
- |payment_method| payment_method.to_string(),
+ .attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
+
+ let tenant_business_profile_id = generate_tenant_business_profile_id(
+ &state.tenant.redis_key_prefix,
+ business_profile.get_id().get_string_repr(),
+ );
+
+ let success_based_connectors = client
+ .calculate_success_rate(
+ tenant_business_profile_id.clone(),
+ success_based_routing_configs.clone(),
+ routable_connectors.clone(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to calculate/fetch success rate from dynamic routing service",
+ )?;
+
+ let payment_status_attribute =
+ get_desired_payment_status_for_success_routing_metrics(&payment_attempt.status);
+
+ let first_success_based_connector_label = &success_based_connectors
+ .labels_with_score
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to fetch the first connector from list of connectors obtained from dynamic routing service",
+ )?
+ .label
+ .to_string();
+
+ let (first_success_based_connector, merchant_connector_id) = first_success_based_connector_label
+ .split_once(':')
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to split connector_name and mca_id from the first connector obtained from dynamic routing service",
+ )?;
+
+ let outcome = get_success_based_metrics_outcome_for_payment(
+ &payment_status_attribute,
+ payment_connector.to_string(),
+ first_success_based_connector.to_string(),
+ );
+
+ core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([
+ ("tenant", state.tenant.name.clone()),
+ (
+ "merchant_id",
+ payment_attempt.merchant_id.get_string_repr().to_string(),
),
- ),
- (
- "payment_method_type",
- payment_attempt.payment_method_type.map_or_else(
- || "None".to_string(),
- |payment_method_type| payment_method_type.to_string(),
+ (
+ "profile_id",
+ payment_attempt.profile_id.get_string_repr().to_string(),
),
- ),
- (
- "capture_method",
- payment_attempt.capture_method.map_or_else(
- || "None".to_string(),
- |capture_method| capture_method.to_string(),
+ ("merchant_connector_id", merchant_connector_id.to_string()),
+ (
+ "payment_id",
+ payment_attempt.payment_id.get_string_repr().to_string(),
),
- ),
- (
- "authentication_type",
- payment_attempt.authentication_type.map_or_else(
- || "None".to_string(),
- |authentication_type| authentication_type.to_string(),
+ (
+ "success_based_routing_connector",
+ first_success_based_connector.to_string(),
),
- ),
- ("payment_status", payment_attempt.status.to_string()),
- ("conclusive_classification", outcome.to_string()),
- ]),
- );
-
- client
- .update_success_rate(
- tenant_business_profile_id,
- success_based_routing_configs,
- vec![routing_types::RoutableConnectorChoiceWithStatus::new(
- routing_types::RoutableConnectorChoice {
- choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
- connector: common_enums::RoutableConnectors::from_str(
- payment_connector.as_str(),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to infer routable_connector from connector")?,
- merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
- },
- payment_status_attribute == common_enums::AttemptStatus::Charged,
- )],
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "unable to update success based routing window in dynamic routing service",
- )?;
- Ok(())
+ ("payment_connector", payment_connector.to_string()),
+ (
+ "currency",
+ payment_attempt
+ .currency
+ .map_or_else(|| "None".to_string(), |currency| currency.to_string()),
+ ),
+ (
+ "payment_method",
+ payment_attempt.payment_method.map_or_else(
+ || "None".to_string(),
+ |payment_method| payment_method.to_string(),
+ ),
+ ),
+ (
+ "payment_method_type",
+ payment_attempt.payment_method_type.map_or_else(
+ || "None".to_string(),
+ |payment_method_type| payment_method_type.to_string(),
+ ),
+ ),
+ (
+ "capture_method",
+ payment_attempt.capture_method.map_or_else(
+ || "None".to_string(),
+ |capture_method| capture_method.to_string(),
+ ),
+ ),
+ (
+ "authentication_type",
+ payment_attempt.authentication_type.map_or_else(
+ || "None".to_string(),
+ |authentication_type| authentication_type.to_string(),
+ ),
+ ),
+ ("payment_status", payment_attempt.status.to_string()),
+ ("conclusive_classification", outcome.to_string()),
+ ]),
+ );
+ logger::debug!("successfully pushed success_based_routing metrics");
+
+ client
+ .update_success_rate(
+ tenant_business_profile_id,
+ success_based_routing_configs,
+ vec![routing_types::RoutableConnectorChoiceWithStatus::new(
+ routing_types::RoutableConnectorChoice {
+ choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
+ connector: common_enums::RoutableConnectors::from_str(
+ payment_connector.as_str(),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to infer routable_connector from connector")?,
+ merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ },
+ payment_status_attribute == common_enums::AttemptStatus::Charged,
+ )],
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "unable to update success based routing window in dynamic routing service",
+ )?;
+ Ok(())
+ } else {
+ Ok(())
+ }
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
@@ -875,3 +892,67 @@ fn get_success_based_metrics_outcome_for_payment(
_ => common_enums::SuccessBasedRoutingConclusiveState::NonDeterministic,
}
}
+
+/// generates cache key with tenant's redis key prefix and profile_id
+pub fn generate_tenant_business_profile_id(
+ redis_key_prefix: &str,
+ business_profile_id: &str,
+) -> String {
+ format!("{}:{}", redis_key_prefix, business_profile_id)
+}
+
+/// default config setup for success_based_routing
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+pub async fn default_success_based_routing_setup(
+ state: &SessionState,
+ key_store: domain::MerchantKeyStore,
+ business_profile: domain::Profile,
+ feature_to_enable: routing_types::SuccessBasedRoutingFeatures,
+ merchant_id: id_type::MerchantId,
+ mut success_based_dynamic_routing_algo: routing_types::DynamicRoutingAlgorithmRef,
+) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
+ let db = state.store.as_ref();
+ let key_manager_state = &state.into();
+ let profile_id = business_profile.get_id().to_owned();
+ let default_success_based_routing_config = routing_types::SuccessBasedRoutingConfig::default();
+ let algorithm_id = common_utils::generate_routing_id_of_default_length();
+ let timestamp = common_utils::date_time::now();
+ let algo = routing_algorithm::RoutingAlgorithm {
+ algorithm_id: algorithm_id.clone(),
+ profile_id: profile_id.clone(),
+ merchant_id,
+ name: SUCCESS_BASED_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.update_algorithm_id(algorithm_id, feature_to_enable);
+ update_business_profile_active_dynamic_algorithm_ref(
+ db,
+ key_manager_state,
+ &key_store,
+ business_profile,
+ success_based_dynamic_routing_algo,
+ )
+ .await?;
+
+ let new_record = record.foreign_into();
+
+ core_metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
+ &metrics::CONTEXT,
+ 1,
+ &add_attributes([("profile_id", profile_id.get_string_repr().to_string())]),
+ );
+ Ok(ApplicationResponse::Json(new_record))
+}
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 4c8d89fa87d..cc4a9510ab6 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -989,7 +989,7 @@ pub async fn toggle_success_based_routing(
) -> impl Responder {
let flow = Flow::ToggleDynamicRouting;
let wrapper = routing_types::ToggleSuccessBasedRoutingWrapper {
- status: query.into_inner().status,
+ feature_to_enable: query.into_inner().enable,
profile_id: path.into_inner().profile_id,
};
Box::pin(oss_api::server_wrap(
@@ -1005,7 +1005,7 @@ pub async fn toggle_success_based_routing(
state,
auth.merchant_account,
auth.key_store,
- wrapper.status,
+ wrapper.feature_to_enable,
wrapper.profile_id,
)
},
|
2024-10-16T04:25:05Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This will add dynamic_routing in core flows.
After which once the toggle route is hit with `feature = dynamic_connector_selection`, routable connectors will be evaluated on basis of success_based routing.
### 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).
-->
Will enable success_based routing
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### The testing flows are as follows:
1. Toggle the route with feature(`metrics`, `dynamic_conenctor_selection`, `none`) as `dynamic_connector_selection`.
```
curl --location --request POST 'http://localhost:8080/account/merchant_id/business_profile/profile_id/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \
--header 'api-key: api_key'
```
2. Check the business_profile table for the enabled dynamic routing feature.
3. Moreover if the dynamic_connector_selection is enabled for business_profile, success_based_routing will be performed, which can be checked by having a log filter with `success_based_routing connectors`.
4. If metrics feature is enabled, there will be no logs from the 3rd step instead there will be a log something like `successfully pushed success_based_routing metrics`, NOTE: this log will also be present in step 3rd.
5. if None is selected no logs regarding `success_based_routing` will be there.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
39d89f23b6ae85c4f91a52bb0d970277b43237d8
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6348
|
Bug: set the eligible connector in payment attempt for network transaction id based mit flow
[Reference pr](https://github.com/juspay/hyperswitch/pull/6245)
In the MIT flow when the recurring details is of type `"type": "network_transaction_id_and_card_details"` the eligible connector needs to be set in the payment attempt.
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 68f318958a2..a6ddc2e2180 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4193,6 +4193,10 @@ where
}
};
+ // Set the eligible connector in the attempt
+ payment_data
+ .set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string()));
+
// Set `NetworkMandateId` as the MandateId
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
|
2024-10-17T07:50:34Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
In the MIT flow when the recurring details is of type "type": "network_transaction_id_and_card_details" the eligible connector needs to be set in the payment attempt.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test 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 for cybersource
-> Make a MIT payment with `"type": "network_transaction_id_and_card_details"`
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'api-key: dev_OJYRaFClX8PIIwCNrPWUMttJWZrAXUNbBiyA1GvyYyaxRK5EsqODd2ON8KTOlTMa' \
--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_ZEs9n2F6Yp0oy50G8VmN",
"merchant_id": "merchant_1729157921",
"status": "succeeded",
"amount": 499,
"net_amount": 499,
"amount_capturable": 0,
"amount_received": 499,
"connector": "cybersource",
"client_secret": "pay_ZEs9n2F6Yp0oy50G8VmN_secret_fC2BsOIUxNEDzAtimD0X",
"created": "2024-10-17T09:39:04.760Z",
"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": "7291579463536087703954",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_ZEs9n2F6Yp0oy50G8VmN_1",
"payment_link": null,
"profile_id": "pro_F0y6R0BOaHFdIv6wsaT8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HMDXW38hX91dX1Z5z1xC",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-17T09:54:04.760Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-17T09:39:07.091Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
881f5fd0149cb5573eb31451fceb596092eab79a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6318
|
Bug: docs: Adding Unified error codes to the API - Ref
Adding Unified error codes to the API - Ref
|
2024-10-15T10:13:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [X] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Helps closing - #6318
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d06d19fc96e1a74d20e2fe3613f86d541947e0ae
|
||
juspay/hyperswitch
|
juspay__hyperswitch-6312
|
Bug: replace underscore by hyphen in Samsung pay session call
replace underscore by hyphen in Samsung pay session call as it is passed to samsung pay as `order_number`. And Samsung pay does not accept underscore
|
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 1785eee87c5..053c9b8fb0a 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -567,13 +567,15 @@ fn create_samsung_pay_session_token(
})?,
};
+ let formatted_payment_id = router_data.payment_id.replace("_", "-");
+
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.service_id,
- order_number: router_data.payment_id.clone(),
+ order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
|
2024-10-14T14:59:59Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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 connector 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_1728548597"
}'
```
```
{
"payment_id": "pay_mJFt25nBNl0ZKeW122Eu",
"merchant_id": "merchant_1728917453",
"status": "requires_payment_method",
"amount": 100000,
"net_amount": 100000,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ",
"created": "2024-10-14T14:51:05.156Z",
"currency": "USD",
"customer_id": "cu_1728548597",
"customer": {
"id": "cu_1728548597",
"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_1728548597",
"created_at": 1728917465,
"expires": 1728921065,
"secret": "epk_cd0634f3e55a456aab914f0715a37cbd"
},
"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_a54a9pfTV5Yf5U2wboZ2",
"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-14T15:06:05.156Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-10-14T14:51:05.213Z",
"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_f89f808cd23b4b53ba1f84d1ae675e3c' \
--data '{
"payment_id": "pay_mJFt25nBNl0ZKeW122Eu",
"wallets": [],
"client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ"
}'
```
```
{
"payment_id": "pay_mJFt25nBNl0ZKeW122Eu",
"client_secret": "pay_mJFt25nBNl0ZKeW122Eu_secret_ssXacvSHe4w7Q6smAWOQ",
"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-mJFt25nBNl0ZKeW122Eu",
"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
}
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
df280f2574ac701a5e32b9bcae90c87cab7bc5aa
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a7c6f57668683132ac3b59a0398742ea9d12bdca
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6314
|
Bug: [FEAT] add a macro to derive ToEncryptable trait
|
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index eb196a72074..4f6411a42cd 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -1,12 +1,5 @@
-use common_utils::{
- crypto, custom_serde,
- encryption::Encryption,
- id_type,
- pii::{self, EmailStrategy},
- types::{keymanager::ToEncryptable, Description},
-};
-use masking::{ExposeInterface, Secret, SwitchStrategy};
-use rustc_hash::FxHashMap;
+use common_utils::{crypto, custom_serde, id_type, pii, types::Description};
+use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -129,85 +122,6 @@ impl CustomerRequest {
}
}
-pub struct CustomerRequestWithEmail {
- pub name: Option<Secret<String>>,
- pub email: Option<pii::Email>,
- pub phone: Option<Secret<String>>,
-}
-
-pub struct CustomerRequestWithEncryption {
- pub name: Option<Encryption>,
- pub phone: Option<Encryption>,
- pub email: Option<Encryption>,
-}
-
-pub struct EncryptableCustomer {
- pub name: crypto::OptionalEncryptableName,
- pub phone: crypto::OptionalEncryptablePhone,
- pub email: crypto::OptionalEncryptableEmail,
-}
-
-impl ToEncryptable<EncryptableCustomer, Secret<String>, Encryption>
- for CustomerRequestWithEncryption
-{
- fn to_encryptable(self) -> FxHashMap<String, Encryption> {
- let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default());
- self.name.map(|x| map.insert("name".to_string(), x));
- self.phone.map(|x| map.insert("phone".to_string(), x));
- self.email.map(|x| map.insert("email".to_string(), x));
- map
- }
-
- fn from_encryptable(
- mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>,
- ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError>
- {
- Ok(EncryptableCustomer {
- name: hashmap.remove("name"),
- phone: hashmap.remove("phone"),
- email: hashmap.remove("email").map(|email| {
- let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> =
- crypto::Encryptable::new(
- email.clone().into_inner().switch_strategy(),
- email.into_encrypted(),
- );
- encryptable
- }),
- })
- }
-}
-
-impl ToEncryptable<EncryptableCustomer, Secret<String>, Secret<String>>
- for CustomerRequestWithEmail
-{
- fn to_encryptable(self) -> FxHashMap<String, Secret<String>> {
- let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default());
- self.name.map(|x| map.insert("name".to_string(), x));
- self.phone.map(|x| map.insert("phone".to_string(), x));
- self.email
- .map(|x| map.insert("email".to_string(), x.expose().switch_strategy()));
- map
- }
-
- fn from_encryptable(
- mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>,
- ) -> common_utils::errors::CustomResult<EncryptableCustomer, common_utils::errors::ParsingError>
- {
- Ok(EncryptableCustomer {
- name: hashmap.remove("name"),
- email: hashmap.remove("email").map(|email| {
- let encryptable: crypto::Encryptable<Secret<String, EmailStrategy>> =
- crypto::Encryptable::new(
- email.clone().into_inner().switch_strategy(),
- email.into_encrypted(),
- );
- encryptable
- }),
- phone: hashmap.remove("phone"),
- })
- }
-}
-
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct CustomerResponse {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 2e31c0ba258..4efc2e8d960 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -12,13 +12,12 @@ use common_utils::{
ext_traits::{ConfigExt, Encode, ValueExt},
hashing::HashedString,
id_type,
- pii::{self, Email, EmailStrategy},
- types::{keymanager::ToEncryptable, MinorUnit, StringMajorUnit},
+ pii::{self, Email},
+ types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
-use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy, WithType};
+use masking::{PeekInterface, Secret, WithType};
use router_derive::Setter;
-use rustc_hash::FxHashMap;
use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize};
use strum::Display;
use time::{Date, PrimitiveDateTime};
@@ -3763,54 +3762,6 @@ pub struct EncryptableAddressDetails {
pub email: crypto::OptionalEncryptableEmail,
}
-impl ToEncryptable<EncryptableAddressDetails, Secret<String>, Secret<String>>
- for AddressDetailsWithPhone
-{
- fn from_encryptable(
- mut hashmap: FxHashMap<String, crypto::Encryptable<Secret<String>>>,
- ) -> common_utils::errors::CustomResult<
- EncryptableAddressDetails,
- common_utils::errors::ParsingError,
- > {
- Ok(EncryptableAddressDetails {
- line1: hashmap.remove("line1"),
- line2: hashmap.remove("line2"),
- line3: hashmap.remove("line3"),
- state: hashmap.remove("state"),
- zip: hashmap.remove("zip"),
- first_name: hashmap.remove("first_name"),
- last_name: hashmap.remove("last_name"),
- phone_number: hashmap.remove("phone_number"),
- email: hashmap.remove("email").map(|x| {
- let inner: Secret<String, EmailStrategy> = x.clone().into_inner().switch_strategy();
- crypto::Encryptable::new(inner, x.into_encrypted())
- }),
- })
- }
-
- fn to_encryptable(self) -> FxHashMap<String, Secret<String>> {
- let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default());
- self.address.map(|address| {
- address.line1.map(|x| map.insert("line1".to_string(), x));
- address.line2.map(|x| map.insert("line2".to_string(), x));
- address.line3.map(|x| map.insert("line3".to_string(), x));
- address.state.map(|x| map.insert("state".to_string(), x));
- address.zip.map(|x| map.insert("zip".to_string(), x));
- address
- .first_name
- .map(|x| map.insert("first_name".to_string(), x));
- address
- .last_name
- .map(|x| map.insert("last_name".to_string(), x));
- });
- self.email
- .map(|x| map.insert("email".to_string(), x.expose().switch_strategy()));
- self.phone_number
- .map(|x| map.insert("phone_number".to_string(), x));
- map
- }
-}
-
#[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)]
pub struct PhoneDetails {
/// The contact number
diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs
index a1cfb668716..06b82cb2c20 100644
--- a/crates/diesel_models/src/address.rs
+++ b/crates/diesel_models/src/address.rs
@@ -1,12 +1,5 @@
-use common_utils::{
- crypto::{self, Encryptable},
- encryption::Encryption,
- pii::EmailStrategy,
- types::keymanager::ToEncryptable,
-};
+use common_utils::{crypto, encryption::Encryption};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
-use masking::{Secret, SwitchStrategy};
-use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -74,48 +67,6 @@ pub struct EncryptableAddress {
pub email: crypto::OptionalEncryptableEmail,
}
-impl ToEncryptable<EncryptableAddress, Secret<String>, Encryption> for Address {
- fn to_encryptable(self) -> FxHashMap<String, Encryption> {
- let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default());
- self.line1.map(|x| map.insert("line1".to_string(), x));
- self.line2.map(|x| map.insert("line2".to_string(), x));
- self.line3.map(|x| map.insert("line3".to_string(), x));
- self.zip.map(|x| map.insert("zip".to_string(), x));
- self.state.map(|x| map.insert("state".to_string(), x));
- self.first_name
- .map(|x| map.insert("first_name".to_string(), x));
- self.last_name
- .map(|x| map.insert("last_name".to_string(), x));
- self.phone_number
- .map(|x| map.insert("phone_number".to_string(), x));
- self.email.map(|x| map.insert("email".to_string(), x));
- map
- }
-
- fn from_encryptable(
- mut hashmap: FxHashMap<String, Encryptable<Secret<String>>>,
- ) -> common_utils::errors::CustomResult<EncryptableAddress, common_utils::errors::ParsingError>
- {
- Ok(EncryptableAddress {
- line1: hashmap.remove("line1"),
- line2: hashmap.remove("line2"),
- line3: hashmap.remove("line3"),
- zip: hashmap.remove("zip"),
- state: hashmap.remove("state"),
- first_name: hashmap.remove("first_name"),
- last_name: hashmap.remove("last_name"),
- phone_number: hashmap.remove("phone_number"),
- email: hashmap.remove("email").map(|email| {
- let encryptable: Encryptable<Secret<String, EmailStrategy>> = Encryptable::new(
- email.clone().into_inner().switch_strategy(),
- email.into_encrypted(),
- );
- encryptable
- }),
- })
- }
-}
-
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = address)]
pub struct AddressUpdateInternal {
diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs
index b6c5efe0fd1..82b2b58f80b 100644
--- a/crates/diesel_models/src/events.rs
+++ b/crates/diesel_models/src/events.rs
@@ -1,11 +1,7 @@
-use common_utils::{
- crypto::OptionalEncryptableSecretString, custom_serde, encryption::Encryption,
- types::keymanager::ToEncryptable,
-};
+use common_utils::{custom_serde, encryption::Encryption};
use diesel::{
expression::AsExpression, AsChangeset, Identifiable, Insertable, Queryable, Selectable,
};
-use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -63,38 +59,6 @@ pub struct Event {
pub metadata: Option<EventMetadata>,
}
-pub struct EventWithEncryption {
- pub request: Option<Encryption>,
- pub response: Option<Encryption>,
-}
-
-pub struct EncryptableEvent {
- pub request: OptionalEncryptableSecretString,
- pub response: OptionalEncryptableSecretString,
-}
-
-impl ToEncryptable<EncryptableEvent, Secret<String>, Encryption> for EventWithEncryption {
- fn to_encryptable(self) -> rustc_hash::FxHashMap<String, Encryption> {
- let mut map = rustc_hash::FxHashMap::default();
- self.request.map(|x| map.insert("request".to_string(), x));
- self.response.map(|x| map.insert("response".to_string(), x));
- map
- }
-
- fn from_encryptable(
- mut hashmap: rustc_hash::FxHashMap<
- String,
- common_utils::crypto::Encryptable<Secret<String>>,
- >,
- ) -> common_utils::errors::CustomResult<EncryptableEvent, common_utils::errors::ParsingError>
- {
- Ok(EncryptableEvent {
- request: hashmap.remove("request"),
- response: hashmap.remove("response"),
- })
- }
-}
-
#[derive(Clone, Debug, Deserialize, Serialize, AsExpression, diesel::FromSqlRow)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub enum EventMetadata {
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index 9f079f1312e..71cb4ebc2f9 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -1,8 +1,8 @@
-use api_models::customers::CustomerRequestWithEncryption;
#[cfg(all(feature = "v2", feature = "customer_v2"))]
use common_enums::DeleteStatus;
use common_utils::{
- crypto, date_time,
+ crypto::{self, Encryptable},
+ date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii,
@@ -13,19 +13,23 @@ use common_utils::{
};
use diesel_models::customers::CustomerUpdateInternal;
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
+use masking::{PeekInterface, Secret, SwitchStrategy};
+use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
use crate::type_encryption as types;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
- pub name: crypto::OptionalEncryptableName,
- pub email: crypto::OptionalEncryptableEmail,
- pub phone: crypto::OptionalEncryptablePhone,
+ #[encrypt]
+ pub name: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
+ #[encrypt]
+ pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
@@ -39,12 +43,15 @@ pub struct Customer {
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub merchant_id: id_type::MerchantId,
- pub name: crypto::OptionalEncryptableName,
- pub email: crypto::OptionalEncryptableEmail,
- pub phone: crypto::OptionalEncryptablePhone,
+ #[encrypt]
+ pub name: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
+ #[encrypt]
+ pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
@@ -98,8 +105,8 @@ impl super::behaviour::Conversion for Customer {
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
- types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable(
- CustomerRequestWithEncryption {
+ types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
+ EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
@@ -113,16 +120,23 @@ impl super::behaviour::Conversion for Customer {
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
- let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted)
- .change_context(ValidationError::InvalidValue {
+ let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
+ ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
- })?;
+ },
+ )?;
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
@@ -198,8 +212,8 @@ impl super::behaviour::Conversion for Customer {
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
- types::CryptoOperation::BatchDecrypt(CustomerRequestWithEncryption::to_encryptable(
- CustomerRequestWithEncryption {
+ types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
+ EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
@@ -213,17 +227,24 @@ impl super::behaviour::Conversion for Customer {
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
- let encryptable_customer = CustomerRequestWithEncryption::from_encryptable(decrypted)
- .change_context(ValidationError::InvalidValue {
+ let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
+ ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
- })?;
+ },
+ )?;
Ok(Self {
id: item.id,
merchant_reference_id: item.merchant_reference_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 9418f6f8f1e..0d730be203b 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -10,16 +10,18 @@ use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountU
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
+use serde_json::Value;
use super::behaviour;
use crate::type_encryption::{crypto_operation, CryptoOperation};
#[cfg(feature = "v1")]
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
- pub connector_account_details: Encryptable<pii::SecretSerdeValue>,
+ #[encrypt]
+ pub connector_account_details: Encryptable<Secret<Value>>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
@@ -38,8 +40,10 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
- pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
- pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+ #[encrypt]
+ pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
+ #[encrypt]
+ pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
}
@@ -51,12 +55,13 @@ impl MerchantConnectorAccount {
}
#[cfg(feature = "v2")]
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub id: id_type::MerchantConnectorAccountId,
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
- pub connector_account_details: Encryptable<pii::SecretSerdeValue>,
+ #[encrypt]
+ pub connector_account_details: Encryptable<Secret<Value>>,
pub disabled: Option<bool>,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub connector_type: enums::ConnectorType,
@@ -70,8 +75,10 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
- pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>,
- pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>,
+ #[encrypt]
+ pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
+ #[encrypt]
+ pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
}
@@ -179,11 +186,13 @@ impl behaviour::Conversion for MerchantConnectorAccount {
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,
- })),
+ CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
+ EncryptedMerchantConnectorAccount {
+ 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(),
)
@@ -193,11 +202,10 @@ impl behaviour::Conversion for MerchantConnectorAccount {
message: "Failed while decrypting connector account details".to_string(),
})?;
- let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context(
- ValidationError::InvalidValue {
+ let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
+ .change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
- },
- )?;
+ })?;
Ok(Self {
merchant_id: other.merchant_id,
@@ -308,11 +316,13 @@ impl behaviour::Conversion for MerchantConnectorAccount {
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,
- })),
+ CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
+ EncryptedMerchantConnectorAccount {
+ 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(),
)
@@ -322,11 +332,10 @@ impl behaviour::Conversion for MerchantConnectorAccount {
message: "Failed while decrypting connector account details".to_string(),
})?;
- let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context(
- ValidationError::InvalidValue {
+ let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
+ .change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
- },
- )?;
+ })?;
Ok(Self {
id: other.id,
@@ -502,121 +511,3 @@ 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/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 933c13416f2..cd41458dfbf 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -5,11 +5,21 @@ use std::marker::PhantomData;
use api_models::payments::Address;
#[cfg(feature = "v2")]
use api_models::payments::OrderDetailsWithAmount;
-use common_utils::{self, crypto::Encryptable, id_type, pii, types::MinorUnit};
+use common_utils::{
+ self,
+ crypto::Encryptable,
+ encryption::Encryption,
+ errors::CustomResult,
+ id_type, pii,
+ types::{keymanager::ToEncryptable, MinorUnit},
+};
use diesel_models::payment_intent::TaxDetails;
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use masking::Secret;
+use router_derive::ToEncryption;
+use rustc_hash::FxHashMap;
+use serde_json::Value;
use time::PrimitiveDateTime;
pub mod payment_attempt;
@@ -25,7 +35,7 @@ use crate::{business_profile, merchant_account};
use crate::{errors, payment_method_data, ApiModelToDieselModelConvertor};
#[cfg(feature = "v1")]
-#[derive(Clone, Debug, PartialEq, serde::Serialize)]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
@@ -37,7 +47,7 @@ pub struct PaymentIntent {
pub customer_id: Option<id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
- pub metadata: Option<serde_json::Value>,
+ pub metadata: Option<Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
@@ -56,9 +66,9 @@ pub struct PaymentIntent {
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
- pub allowed_payment_method_types: Option<serde_json::Value>,
- pub connector_metadata: Option<serde_json::Value>,
- pub feature_metadata: Option<serde_json::Value>,
+ pub allowed_payment_method_types: Option<Value>,
+ pub connector_metadata: Option<Value>,
+ pub feature_metadata: Option<Value>,
pub attempt_count: i16,
pub profile_id: Option<id_type::ProfileId>,
pub payment_link_id: Option<String>,
@@ -78,10 +88,13 @@ pub struct PaymentIntent {
pub request_external_three_ds_authentication: Option<bool>,
pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
- pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
- pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ #[encrypt]
+ pub customer_details: Option<Encryptable<Secret<Value>>>,
+ #[encrypt]
+ pub billing_details: Option<Encryptable<Secret<Value>>>,
pub merchant_order_reference_id: Option<String>,
- pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ #[encrypt]
+ pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
@@ -225,7 +238,7 @@ impl AmountDetails {
}
#[cfg(feature = "v2")]
-#[derive(Clone, Debug, PartialEq, serde::Serialize)]
+#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
/// The global identifier for the payment intent. This is generated by the system.
/// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`.
@@ -292,19 +305,22 @@ pub struct PaymentIntent {
/// Metadata related to fraud and risk management
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// The details of the customer in a denormalized form. Only a subset of fields are stored.
- pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ #[encrypt]
+ pub customer_details: Option<Encryptable<Secret<Value>>>,
/// The reference id for the order in the merchant's system. This value can be passed by the merchant.
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The billing address for the order in a denormalized form.
+ #[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Secret<Address>>>,
/// The shipping address for the order in a denormalized form.
+ #[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<Secret<Address>>>,
/// Capture method for the payment
pub capture_method: storage_enums::CaptureMethod,
/// Authentication type that is requested by the merchant for this payment.
pub authentication_type: common_enums::AuthenticationType,
/// This contains the pre routing results that are done when routing is done during listing the payment methods.
- pub prerouting_algorithm: Option<serde_json::Value>,
+ pub prerouting_algorithm: Option<Value>,
/// The organization id for the payment. This is derived from the merchant account
pub organization_id: id_type::OrganizationId,
/// Denotes the request by the merchant whether to enable a payment link for this payment.
@@ -323,7 +339,7 @@ pub struct PaymentIntent {
impl PaymentIntent {
fn get_request_incremental_authorization_value(
request: &api_models::payments::PaymentsCreateIntentRequest,
- ) -> common_utils::errors::CustomResult<
+ ) -> CustomResult<
common_enums::RequestIncrementalAuthorization,
errors::api_error_response::ApiErrorResponse,
> {
@@ -364,8 +380,7 @@ impl PaymentIntent {
request: api_models::payments::PaymentsCreateIntentRequest,
billing_address: Option<Encryptable<Secret<Address>>>,
shipping_address: Option<Encryptable<Secret<Address>>>,
- ) -> common_utils::errors::CustomResult<Self, errors::api_error_response::ApiErrorResponse>
- {
+ ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index f1e4de499e6..c9f7a5e2ae5 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -3,7 +3,7 @@ use common_enums as storage_enums;
use common_utils::ext_traits::{Encode, ValueExt};
use common_utils::{
consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2},
- crypto::{self, Encryptable},
+ crypto::Encryptable,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type,
@@ -21,7 +21,6 @@ use error_stack::ResultExt;
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::{Deserialize, PeekInterface, Secret};
-use rustc_hash::FxHashMap;
use serde::Serialize;
use time::PrimitiveDateTime;
@@ -1241,10 +1240,10 @@ impl behaviour::Conversion for PaymentIntent {
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,
+ CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(
+ super::EncryptedPaymentIntent {
+ billing_address: storage_model.billing_address,
+ shipping_address: storage_model.shipping_address,
customer_details: storage_model.customer_details,
},
)),
@@ -1254,7 +1253,7 @@ impl behaviour::Conversion for PaymentIntent {
.await
.and_then(|val| val.try_into_batchoperation())?;
- let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data)
+ let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
@@ -1275,7 +1274,7 @@ impl behaviour::Conversion for PaymentIntent {
};
let billing_address = data
- .billing
+ .billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
@@ -1284,7 +1283,7 @@ impl behaviour::Conversion for PaymentIntent {
.attach_printable("Error while deserializing Address")?;
let shipping_address = data
- .shipping
+ .shipping_address
.map(|shipping| {
shipping.deserialize_inner_value(|value| value.parse_value("Address"))
})
@@ -1513,10 +1512,10 @@ impl behaviour::Conversion for PaymentIntent {
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,
+ CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(
+ super::EncryptedPaymentIntent {
+ billing_details: storage_model.billing_details,
+ shipping_details: storage_model.shipping_details,
customer_details: storage_model.customer_details,
},
)),
@@ -1526,7 +1525,7 @@ impl behaviour::Conversion for PaymentIntent {
.await
.and_then(|val| val.try_into_batchoperation())?;
- let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data)
+ let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
@@ -1578,9 +1577,9 @@ impl behaviour::Conversion for PaymentIntent {
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
customer_details: data.customer_details,
- billing_details: data.billing,
+ billing_details: data.billing_details,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
- shipping_details: data.shipping,
+ shipping_details: data.shipping_details,
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,
@@ -1649,73 +1648,3 @@ 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/src/core/admin.rs b/crates/router/src/core/admin.rs
index f49f4096340..cffb8267bff 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -15,7 +15,7 @@ use diesel_models::configs;
use diesel_models::organization::OrganizationBridge;
use error_stack::{report, FutureExt, ResultExt};
use hyperswitch_domain_models::merchant_connector_account::{
- McaFromRequest, McaFromRequestfromUpdate,
+ FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types};
@@ -2095,18 +2095,20 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
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),
- },
- )),
+ domain_types::CryptoOperation::BatchEncrypt(
+ UpdateEncryptableMerchantConnectorAccount::to_encryptable(
+ UpdateEncryptableMerchantConnectorAccount {
+ 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(),
)
@@ -2115,9 +2117,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
.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")?;
+ let encrypted_data =
+ UpdateEncryptableMerchantConnectorAccount::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),
@@ -2262,18 +2265,20 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
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),
- },
- )),
+ domain_types::CryptoOperation::BatchEncrypt(
+ UpdateEncryptableMerchantConnectorAccount::to_encryptable(
+ UpdateEncryptableMerchantConnectorAccount {
+ 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(),
)
@@ -2282,9 +2287,10 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
.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")?;
+ let encrypted_data =
+ UpdateEncryptableMerchantConnectorAccount::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),
@@ -2404,22 +2410,24 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
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),
- },
- )),
+ domain_types::CryptoOperation::BatchEncrypt(
+ FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
+ FromRequestEncryptableMerchantConnectorAccount {
+ 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(),
)
@@ -2428,9 +2436,10 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
.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")?;
+ let encrypted_data =
+ FromRequestEncryptableMerchantConnectorAccount::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(),
@@ -2573,22 +2582,24 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
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),
- },
- )),
+ domain_types::CryptoOperation::BatchEncrypt(
+ FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
+ FromRequestEncryptableMerchantConnectorAccount {
+ 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(),
)
@@ -2597,9 +2608,10 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
.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")?;
+ let encrypted_data =
+ FromRequestEncryptableMerchantConnectorAccount::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(),
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 18cc8682eee..6d47ac174f3 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,16 +1,15 @@
-use api_models::customers::CustomerRequestWithEmail;
use common_utils::{
crypto::Encryptable,
errors::ReportSwitchExt,
ext_traits::{AsyncExt, OptionExt},
- id_type, type_name,
+ id_type, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
Description,
},
};
use error_stack::{report, ResultExt};
-use masking::{Secret, SwitchStrategy};
+use masking::{ExposeInterface, Secret, SwitchStrategy};
use router_env::{instrument, tracing};
#[cfg(all(feature = "v2", feature = "customer_v2"))]
@@ -145,13 +144,15 @@ impl CustomerCreateBridge for customers::CustomerRequest {
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: self.name.clone(),
- email: self.email.clone(),
- phone: self.phone.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: self.name.clone(),
+ email: self.email.clone().map(|a| a.expose().switch_strategy()),
+ phone: self.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -160,8 +161,9 @@ impl CustomerCreateBridge for customers::CustomerRequest {
.switch()
.attach_printable("Failed while encrypting Customer")?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+ let encryptable_customer =
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
Ok(domain::Customer {
customer_id: merchant_reference_id
@@ -169,7 +171,13 @@ impl CustomerCreateBridge for customers::CustomerRequest {
.ok_or(errors::CustomersErrorResponse::InternalServerError)?,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
@@ -234,13 +242,15 @@ impl CustomerCreateBridge for customers::CustomerRequest {
let encrypted_data = types::crypto_operation(
key_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: Some(self.name.clone()),
- email: Some(self.email.clone()),
- phone: self.phone.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: Some(self.name.clone()),
+ email: Some(self.email.clone().expose().switch_strategy()),
+ phone: self.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -249,15 +259,22 @@ impl CustomerCreateBridge for customers::CustomerRequest {
.switch()
.attach_printable("Failed while encrypting Customer")?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+ let encryptable_customer =
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
Ok(domain::Customer {
id: common_utils::generate_time_ordered_id("cus"),
merchant_reference_id: merchant_reference_id.to_owned(),
merchant_id,
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
@@ -1174,13 +1191,18 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: self.name.clone(),
- email: self.email.clone(),
- phone: self.phone.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: self.name.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ phone: self.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -1188,8 +1210,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
.and_then(|val| val.try_into_batchoperation())
.switch()?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+ let encryptable_customer =
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_customer_id_merchant_id(
@@ -1199,7 +1222,14 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
domain_customer.to_owned(),
storage::CustomerUpdate::Update {
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: Box::new(encryptable_customer.phone),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
@@ -1266,13 +1296,18 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: self.name.clone(),
- email: self.email.clone(),
- phone: self.phone.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: self.name.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ phone: self.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -1280,8 +1315,9 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
.and_then(|val| val.try_into_batchoperation())
.switch()?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::CustomersErrorResponse::InternalServerError)?;
+ let encryptable_customer =
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
+ .change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_global_id(
@@ -1291,7 +1327,14 @@ impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
merchant_account.get_id(),
storage::CustomerUpdate::Update {
name: encryptable_customer.name,
- email: Box::new(encryptable_customer.email),
+ email: Box::new(encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ })),
phone: Box::new(encryptable_customer.phone),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 1f67e8066c9..ea7af3c7578 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1,12 +1,9 @@
use std::{borrow::Cow, str::FromStr};
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use api_models::customers::CustomerRequestWithEmail;
use api_models::{
mandates::RecurringDetails,
payments::{
- additional_info as payment_additional_types, AddressDetailsWithPhone, PaymentChargeRequest,
- RequestSurchargeDetails,
+ additional_info as payment_additional_types, PaymentChargeRequest, RequestSurchargeDetails,
},
};
use base64::Engine;
@@ -39,7 +36,7 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject};
use josekit::jwe;
-use masking::{ExposeInterface, PeekInterface};
+use masking::{ExposeInterface, PeekInterface, SwitchStrategy};
use openssl::{
derive::Deriver,
pkey::PKey,
@@ -126,16 +123,33 @@ pub async fn create_or_update_address_for_payment_by_request(
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
- types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: address.address.clone(),
- phone_number: address
- .phone
- .as_ref()
- .and_then(|phone| phone.number.clone()),
- email: address.email.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address.address.as_ref().and_then(|a| a.line1.clone()),
+ line2: address.address.as_ref().and_then(|a| a.line2.clone()),
+ line3: address.address.as_ref().and_then(|a| a.line3.clone()),
+ state: address.address.as_ref().and_then(|a| a.state.clone()),
+ first_name: address
+ .address
+ .as_ref()
+ .and_then(|a| a.first_name.clone()),
+ last_name: address
+ .address
+ .as_ref()
+ .and_then(|a| a.last_name.clone()),
+ zip: address.address.as_ref().and_then(|a| a.zip.clone()),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone| phone.number.clone()),
+ email: address
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ },
+ ),
+ ),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
key,
)
@@ -143,9 +157,10 @@ pub async fn create_or_update_address_for_payment_by_request(
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while encrypting address")?;
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting address")?;
let address_update = storage::AddressUpdate::Update {
city: address
.address
@@ -165,7 +180,14 @@ pub async fn create_or_update_address_for_payment_by_request(
.as_ref()
.and_then(|value| value.country_code.clone()),
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
};
let address = db
.find_address_by_merchant_id_payment_id_address_id(
@@ -317,23 +339,35 @@ pub async fn get_domain_address(
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
- types::CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: address_details.cloned(),
- phone_number: address
- .phone
- .as_ref()
- .and_then(|phone| phone.number.clone()),
- email: address.email.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address.address.as_ref().and_then(|a| a.line1.clone()),
+ line2: address.address.as_ref().and_then(|a| a.line2.clone()),
+ line3: address.address.as_ref().and_then(|a| a.line3.clone()),
+ state: address.address.as_ref().and_then(|a| a.state.clone()),
+ first_name: address.address.as_ref().and_then(|a| a.first_name.clone()),
+ last_name: address.address.as_ref().and_then(|a| a.last_name.clone()),
+ zip: address.address.as_ref().and_then(|a| a.zip.clone()),
+ phone_number: address
+ .phone
+ .as_ref()
+ .and_then(|phone| phone.number.clone()),
+ email: address
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
+ },
+ ),
+ ),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(domain::Address {
phone_number: encryptable_address.phone_number,
country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()),
@@ -351,7 +385,14 @@ pub async fn get_domain_address(
modified_at: common_utils::date_time::now(),
zip: encryptable_address.zip,
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
})
}
.await
@@ -1589,13 +1630,18 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
- types::CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: request_customer_details.name.clone(),
- email: request_customer_details.email.clone(),
- phone: request_customer_details.phone.clone(),
- },
- )),
+ types::CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: request_customer_details.name.clone(),
+ email: request_customer_details
+ .email
+ .as_ref()
+ .map(|e| e.clone().expose().switch_strategy()),
+ phone: request_customer_details.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -1603,9 +1649,10 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
- let encryptable_customer = CustomerRequestWithEmail::from_encryptable(encrypted_data)
- .change_context(errors::StorageError::SerializationFailed)
- .attach_printable("Failed while encrypting Customer while Update")?;
+ let encryptable_customer =
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
+ .change_context(errors::StorageError::SerializationFailed)
+ .attach_printable("Failed while encrypting Customer while Update")?;
Some(match customer_data {
Some(c) => {
// Update the customer data if new data is passed in the request
@@ -1616,7 +1663,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
{
let customer_update = Update {
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<
+ masking::Secret<String, pii::EmailStrategy>,
+ > = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: Box::new(encryptable_customer.phone),
phone_country_code: request_customer_details.phone_country_code,
description: None,
@@ -1644,7 +1699,15 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
customer_id,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<
+ masking::Secret<String, pii::EmailStrategy>,
+ > = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
phone_country_code: request_customer_details.phone_country_code.clone(),
description: None,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 696bd1468e4..13c589c11cc 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -18,8 +18,8 @@ use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::{
- payment_attempt::PaymentAttempt,
- payment_intent::{CustomerData, PaymentAddressFromRequest},
+ payment_attempt::PaymentAttempt, payment_intent::CustomerData,
+ FromRequestEncryptablePaymentIntent,
},
};
use masking::{ExposeInterface, PeekInterface, Secret};
@@ -1340,11 +1340,13 @@ impl PaymentCreate {
&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,
- }),
+ FromRequestEncryptablePaymentIntent::to_encryptable(
+ FromRequestEncryptablePaymentIntent {
+ shipping_details: shipping_details_encoded,
+ billing_details: billing_details_encoded,
+ customer_details: customer_details_encoded,
+ },
+ ),
),
identifier.clone(),
key,
@@ -1354,7 +1356,7 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt data")?;
- let encrypted_data = PaymentAddressFromRequest::from_encryptable(encrypted_data)
+ let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt the payment intent data")?;
@@ -1407,10 +1409,10 @@ impl PaymentCreate {
.request_external_three_ds_authentication,
charges,
frm_metadata: request.frm_metadata.clone(),
- billing_details: encrypted_data.billing,
+ billing_details: encrypted_data.billing_details,
customer_details: encrypted_data.customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
- shipping_details: encrypted_data.shipping,
+ shipping_details: encrypted_data.shipping_details,
is_payment_processor_token_flow,
organization_id: merchant_account.organization_id.clone(),
shipping_cost: request.shipping_cost,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 46f45905448..49b18e53a0c 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -1,11 +1,10 @@
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use api_models::customers::CustomerRequestWithEmail;
use api_models::{enums, payment_methods::Card, payouts};
use common_utils::{
+ crypto::Encryptable,
encryption::Encryption,
errors::CustomResult,
ext_traits::{AsyncExt, StringExt},
- fp_utils, id_type, payout_method_utils as payout_additional, type_name,
+ fp_utils, id_type, payout_method_utils as payout_additional, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit, UnifiedCode, UnifiedMessage,
@@ -15,7 +14,7 @@ use common_utils::{
use common_utils::{generate_customer_id_of_default_length, types::keymanager::ToEncryptable};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy};
use router_env::logger;
use super::PayoutData;
@@ -696,13 +695,18 @@ pub(super) async fn get_or_create_customer_details(
let encrypted_data = crypto_operation(
&state.into(),
type_name!(domain::Customer),
- CryptoOperation::BatchEncrypt(CustomerRequestWithEmail::to_encryptable(
- CustomerRequestWithEmail {
- name: customer_details.name.clone(),
- email: customer_details.email.clone(),
- phone: customer_details.phone.clone(),
- },
- )),
+ CryptoOperation::BatchEncrypt(
+ domain::FromRequestEncryptableCustomer::to_encryptable(
+ domain::FromRequestEncryptableCustomer {
+ name: customer_details.name.clone(),
+ email: customer_details
+ .email
+ .clone()
+ .map(|a| a.expose().switch_strategy()),
+ phone: customer_details.phone.clone(),
+ },
+ ),
+ ),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
@@ -711,7 +715,7 @@ pub(super) async fn get_or_create_customer_details(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt customer")?;
let encryptable_customer =
- CustomerRequestWithEmail::from_encryptable(encrypted_data)
+ domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form EncryptableCustomer")?;
@@ -719,7 +723,14 @@ pub(super) async fn get_or_create_customer_details(
customer_id: customer_id.clone(),
merchant_id: merchant_id.to_owned().clone(),
name: encryptable_customer.name,
- email: encryptable_customer.email,
+ email: encryptable_customer.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
phone: encryptable_customer.phone,
description: None,
phone_country_code: customer_details.phone_country_code.to_owned(),
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index 5d9af527cd4..2d1e98ec1b8 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -4,30 +4,38 @@ use common_utils::{
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
- id_type, type_name,
+ id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
use diesel_models::{address::AddressUpdateInternal, enums};
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
+use masking::{PeekInterface, Secret, SwitchStrategy};
use rustc_hash::FxHashMap;
use time::{OffsetDateTime, PrimitiveDateTime};
use super::{behaviour, types};
-#[derive(Clone, Debug, serde::Serialize)]
+#[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)]
pub struct Address {
pub address_id: String,
pub city: Option<String>,
pub country: Option<enums::CountryAlpha2>,
- pub line1: crypto::OptionalEncryptableSecretString,
- pub line2: crypto::OptionalEncryptableSecretString,
- pub line3: crypto::OptionalEncryptableSecretString,
- pub state: crypto::OptionalEncryptableSecretString,
- pub zip: crypto::OptionalEncryptableSecretString,
- pub first_name: crypto::OptionalEncryptableSecretString,
- pub last_name: crypto::OptionalEncryptableSecretString,
- pub phone_number: crypto::OptionalEncryptableSecretString,
+ #[encrypt]
+ pub line1: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub line2: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub line3: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub state: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub zip: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub first_name: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub last_name: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub phone_number: Option<Encryptable<Secret<String>>>,
pub country_code: Option<String>,
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
@@ -37,7 +45,8 @@ pub struct Address {
pub modified_at: PrimitiveDateTime,
pub merchant_id: id_type::MerchantId,
pub updated_by: String,
- pub email: crypto::OptionalEncryptableEmail,
+ #[encrypt]
+ pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
}
/// Based on the flow, appropriate address has to be used
@@ -191,8 +200,18 @@ impl behaviour::Conversion for Address {
let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation(
state,
type_name!(Self::DstType),
- types::CryptoOperation::BatchDecrypt(diesel_models::Address::to_encryptable(
- other.clone(),
+ types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable(
+ EncryptedAddress {
+ line1: other.line1,
+ line2: other.line2,
+ line3: other.line3,
+ state: other.state,
+ zip: other.zip,
+ first_name: other.first_name,
+ last_name: other.last_name,
+ phone_number: other.phone_number,
+ email: other.email,
+ },
)),
identifier.clone(),
key.peek(),
@@ -202,10 +221,11 @@ impl behaviour::Conversion for Address {
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
})?;
- let encryptable_address = diesel_models::Address::from_encryptable(decrypted)
- .change_context(ValidationError::InvalidValue {
+ let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context(
+ ValidationError::InvalidValue {
message: "Failed while decrypting".to_string(),
- })?;
+ },
+ )?;
Ok(Self {
address_id: other.address_id,
city: other.city,
@@ -223,7 +243,13 @@ impl behaviour::Conversion for Address {
modified_at: other.modified_at,
updated_by: other.updated_by,
merchant_id: other.merchant_id,
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
})
}
diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs
index badbb9df7b4..db2d7530164 100644
--- a/crates/router/src/types/domain/event.rs
+++ b/crates/router/src/types/domain/event.rs
@@ -1,22 +1,23 @@
use common_utils::{
- crypto::OptionalEncryptableSecretString,
+ crypto::{Encryptable, OptionalEncryptableSecretString},
+ encryption::Encryption,
type_name,
types::keymanager::{KeyManagerState, ToEncryptable},
};
use diesel_models::{
enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt},
events::{EventMetadata, EventUpdateInternal},
- EventWithEncryption,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
+use rustc_hash::FxHashMap;
use crate::{
errors::{CustomResult, ValidationError},
types::domain::types,
};
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Event {
pub event_id: String,
pub event_type: EventType,
@@ -30,8 +31,10 @@ pub struct Event {
pub primary_object_created_at: Option<time::PrimitiveDateTime>,
pub idempotent_event_id: Option<String>,
pub initial_attempt_id: Option<String>,
- pub request: OptionalEncryptableSecretString,
- pub response: OptionalEncryptableSecretString,
+ #[encrypt]
+ pub request: Option<Encryptable<Secret<String>>>,
+ #[encrypt]
+ pub response: Option<Encryptable<Secret<String>>>,
pub delivery_attempt: Option<WebhookDeliveryAttempt>,
pub metadata: Option<EventMetadata>,
}
@@ -96,12 +99,10 @@ impl super::behaviour::Conversion for Event {
let decrypted = types::crypto_operation(
state,
type_name!(Self::DstType),
- types::CryptoOperation::BatchDecrypt(EventWithEncryption::to_encryptable(
- EventWithEncryption {
- request: item.request.clone(),
- response: item.response.clone(),
- },
- )),
+ types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent {
+ request: item.request.clone(),
+ response: item.response.clone(),
+ })),
key_manager_identifier,
key.peek(),
)
@@ -110,7 +111,7 @@ impl super::behaviour::Conversion for Event {
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
})?;
- let encryptable_event = EventWithEncryption::from_encryptable(decrypted).change_context(
+ let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting event data".to_string(),
},
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index f56a741dc1a..515c9a94ce8 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -13,8 +13,6 @@ pub mod user_role;
pub mod verify_connector;
use std::fmt::Debug;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use api_models::payments::AddressDetailsWithPhone;
use api_models::{
enums,
payments::{self},
@@ -22,10 +20,10 @@ use api_models::{
};
use common_utils::types::keymanager::KeyManagerState;
pub use common_utils::{
- crypto,
+ crypto::{self, Encryptable},
ext_traits::{ByteSliceExt, BytesExt, Encode, StringExt, ValueExt},
fp_utils::when,
- id_type,
+ id_type, pii,
validation::validate_email,
};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
@@ -38,6 +36,7 @@ pub use hyperswitch_connectors::utils::QrImage;
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation};
+use masking::{ExposeInterface, SwitchStrategy};
use nanoid::nanoid;
use router_env::metrics::add_attributes;
use serde::de::DeserializeOwned;
@@ -779,20 +778,32 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
- CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: Some(address_details.clone()),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address_details.line1.clone(),
+ line2: address_details.line2.clone(),
+ line3: address_details.line3.clone(),
+ state: address_details.state.clone(),
+ first_name: address_details.first_name.clone(),
+ last_name: address_details.last_name.clone(),
+ zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
- email: self.email.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
},
)),
- Identifier::Merchant(merchant_id),
+ Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
Ok(storage::AddressUpdate::Update {
city: address_details.city,
country: address_details.country,
@@ -806,7 +817,14 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
})
}
@@ -822,11 +840,20 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
- CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: Some(address_details.clone()),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address_details.line1.clone(),
+ line2: address_details.line2.clone(),
+ line3: address_details.line3.clone(),
+ state: address_details.state.clone(),
+ first_name: address_details.first_name.clone(),
+ last_name: address_details.last_name.clone(),
+ zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
- email: self.email.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
@@ -834,8 +861,11 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
)
.await
.and_then(|val| val.try_into_batchoperation())?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
let address = domain::Address {
city: address_details.city,
country: address_details.country,
@@ -853,7 +883,14 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
};
Ok(domain::CustomerAddress {
@@ -877,20 +914,31 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
- CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: Some(address_details.clone()),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address_details.line1.clone(),
+ line2: address_details.line2.clone(),
+ line3: address_details.line3.clone(),
+ state: address_details.state.clone(),
+ first_name: address_details.first_name.clone(),
+ last_name: address_details.last_name.clone(),
+ zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
- email: self.email.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
},
)),
- Identifier::Merchant(merchant_id),
+ Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(storage::AddressUpdate::Update {
city: address_details.city,
country: address_details.country,
@@ -904,7 +952,14 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
})
}
@@ -920,11 +975,20 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
let encrypted_data = crypto_operation(
&state.into(),
type_name!(storage::Address),
- CryptoOperation::BatchEncrypt(AddressDetailsWithPhone::to_encryptable(
- AddressDetailsWithPhone {
- address: Some(address_details.clone()),
+ CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableAddress::to_encryptable(
+ domain::FromRequestEncryptableAddress {
+ line1: address_details.line1.clone(),
+ line2: address_details.line2.clone(),
+ line3: address_details.line3.clone(),
+ state: address_details.state.clone(),
+ first_name: address_details.first_name.clone(),
+ last_name: address_details.last_name.clone(),
+ zip: address_details.zip.clone(),
phone_number: self.phone.clone(),
- email: self.email.clone(),
+ email: self
+ .email
+ .as_ref()
+ .map(|a| a.clone().expose().switch_strategy()),
},
)),
Identifier::Merchant(merchant_id.to_owned()),
@@ -932,8 +996,10 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
)
.await
.and_then(|val| val.try_into_batchoperation())?;
- let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data)
- .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
+
+ let encryptable_address =
+ domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
+ .change_context(common_utils::errors::CryptoError::EncodingFailed)?;
let address = domain::Address {
city: address_details.city,
country: address_details.country,
@@ -951,7 +1017,14 @@ impl CustomerAddress for api_models::customers::CustomerUpdateRequest {
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
updated_by: storage_scheme.to_string(),
- email: encryptable_address.email,
+ email: encryptable_address.email.map(|email| {
+ let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
+ Encryptable::new(
+ email.clone().into_inner().switch_strategy(),
+ email.into_encrypted(),
+ );
+ encryptable
+ }),
};
Ok(domain::CustomerAddress {
diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs
index 69865512a37..33edd5e215e 100644
--- a/crates/router_derive/src/lib.rs
+++ b/crates/router_derive/src/lib.rs
@@ -644,6 +644,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token
/// ("address.zip", "941222"),
/// ("email", "test@example.com"),
/// ]
+///
#[proc_macro_derive(FlatStruct)]
pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as syn::DeriveInput);
@@ -749,3 +750,18 @@ pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenSt
pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
macros::generate_permissions_inner(input)
}
+
+/// Generates the ToEncryptable trait for a type
+///
+/// This macro generates the temporary structs which has the fields that needs to be encrypted
+///
+/// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network
+/// fn from_encryptable: Convert the hashmap back to temp struct
+#[proc_macro_derive(ToEncryption, attributes(encrypt))]
+pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
+ let input = syn::parse_macro_input!(input as syn::DeriveInput);
+
+ macros::derive_to_encryption(input)
+ .unwrap_or_else(|err| err.into_compile_error())
+ .into()
+}
diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rs
index 32e6c213ca6..e227c6533e9 100644
--- a/crates/router_derive/src/macros.rs
+++ b/crates/router_derive/src/macros.rs
@@ -4,6 +4,7 @@ pub(crate) mod generate_permissions;
pub(crate) mod generate_schema;
pub(crate) mod misc;
pub(crate) mod operation;
+pub(crate) mod to_encryptable;
pub(crate) mod try_get_enum;
mod helpers;
@@ -17,6 +18,7 @@ pub(crate) use self::{
diesel::{diesel_enum_derive_inner, diesel_enum_text_derive_inner},
generate_permissions::generate_permissions_inner,
generate_schema::polymorphic_macro_derive_inner,
+ to_encryptable::derive_to_encryption,
};
pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
diff --git a/crates/router_derive/src/macros/to_encryptable.rs b/crates/router_derive/src/macros/to_encryptable.rs
new file mode 100644
index 00000000000..dfcfb72169b
--- /dev/null
+++ b/crates/router_derive/src/macros/to_encryptable.rs
@@ -0,0 +1,326 @@
+use std::iter::Iterator;
+
+use quote::{format_ident, quote};
+use syn::{parse::Parse, punctuated::Punctuated, token::Comma, Field, Ident, Type as SynType};
+
+use crate::macros::{helpers::get_struct_fields, misc::get_field_type};
+
+pub struct FieldMeta {
+ _meta_type: Ident,
+ pub value: Ident,
+}
+
+impl Parse for FieldMeta {
+ fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
+ let _meta_type: Ident = input.parse()?;
+ input.parse::<syn::Token![=]>()?;
+ let value: Ident = input.parse()?;
+ Ok(Self { _meta_type, value })
+ }
+}
+
+impl quote::ToTokens for FieldMeta {
+ fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
+ self.value.to_tokens(tokens);
+ }
+}
+
+fn get_encryption_ty_meta(field: &Field) -> Option<FieldMeta> {
+ let attrs = &field.attrs;
+
+ attrs
+ .iter()
+ .flat_map(|s| s.parse_args::<FieldMeta>())
+ .find(|s| s._meta_type.eq("ty"))
+}
+
+fn get_inner_type(path: &syn::TypePath) -> syn::Result<syn::TypePath> {
+ path.path
+ .segments
+ .last()
+ .and_then(|segment| match &segment.arguments {
+ syn::PathArguments::AngleBracketed(args) => args.args.first(),
+ _ => None,
+ })
+ .and_then(|arg| match arg {
+ syn::GenericArgument::Type(SynType::Path(path)) => Some(path.clone()),
+ _ => None,
+ })
+ .ok_or_else(|| {
+ syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "Only path fields are supported",
+ )
+ })
+}
+
+/// This function returns the inner most type recursively
+/// For example:
+///
+/// In the case of `Encryptable<Secret<String>>> this returns String
+fn get_inner_most_type(ty: SynType) -> syn::Result<Ident> {
+ fn get_inner_type_recursive(path: syn::TypePath) -> syn::Result<syn::TypePath> {
+ match get_inner_type(&path) {
+ Ok(inner_path) => get_inner_type_recursive(inner_path),
+ Err(_) => Ok(path),
+ }
+ }
+
+ match ty {
+ SynType::Path(path) => {
+ let inner_path = get_inner_type_recursive(path)?;
+ inner_path
+ .path
+ .segments
+ .last()
+ .map(|last_segment| last_segment.ident.to_owned())
+ .ok_or_else(|| {
+ syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "At least one ident must be specified",
+ )
+ })
+ }
+ _ => Err(syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "Only path fields are supported",
+ )),
+ }
+}
+
+/// This returns the field which implement #[encrypt] attribute
+fn get_encryptable_fields(fields: Punctuated<Field, Comma>) -> Vec<Field> {
+ fields
+ .into_iter()
+ .filter(|field| {
+ field
+ .attrs
+ .iter()
+ .any(|attr| attr.path().is_ident("encrypt"))
+ })
+ .collect()
+}
+
+/// This function returns the inner most type of a field
+fn get_field_and_inner_types(fields: &[Field]) -> Vec<(Field, Ident)> {
+ fields
+ .iter()
+ .flat_map(|field| {
+ get_inner_most_type(field.ty.clone()).map(|field_name| (field.to_owned(), field_name))
+ })
+ .collect()
+}
+
+/// The type of the struct for which the batch encryption/decryption needs to be implemented
+#[derive(PartialEq, Copy, Clone)]
+enum StructType {
+ Encrypted,
+ Decrypted,
+ DecryptedUpdate,
+ FromRequest,
+ Updated,
+}
+
+impl StructType {
+ /// Generates the fields for temporary structs which consists of the fields that should be
+ /// encrypted/decrypted
+ fn generate_struct_fields(&self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> {
+ fields
+ .iter()
+ .map(|(field, inner_ty)| {
+ let provided_ty = get_encryption_ty_meta(field);
+ let is_option = get_field_type(field.ty.clone())
+ .map(|f| f.eq("Option"))
+ .unwrap_or_default();
+ let ident = &field.ident;
+ let inner_ty = if let Some(ref ty) = provided_ty {
+ &ty.value
+ } else {
+ inner_ty
+ };
+ match (self, is_option) {
+ (Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> },
+ (Self::Encrypted, false) => quote! { pub #ident: Encryption },
+ (Self::Decrypted, true) => {
+ quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
+ }
+ (Self::Decrypted, false) => {
+ quote! { pub #ident: Encryptable<Secret<#inner_ty>> }
+ }
+ (Self::DecryptedUpdate, _) => {
+ quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
+ }
+ (Self::FromRequest, true) => {
+ quote! { pub #ident: Option<Secret<#inner_ty>> }
+ }
+ (Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> },
+ (Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> },
+ }
+ })
+ .collect()
+ }
+
+ /// Generates the ToEncryptable trait implementation
+ fn generate_impls(
+ &self,
+ gen1: proc_macro2::TokenStream,
+ gen2: proc_macro2::TokenStream,
+ gen3: proc_macro2::TokenStream,
+ impl_st: proc_macro2::TokenStream,
+ inner: &[Field],
+ ) -> proc_macro2::TokenStream {
+ let map_length = inner.len();
+
+ let to_encryptable_impl = inner.iter().flat_map(|field| {
+ get_field_type(field.ty.clone()).map(|field_ty| {
+ let is_option = field_ty.eq("Option");
+ let field_ident = &field.ident;
+ let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
+
+ if is_option || *self == Self::Updated {
+ quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) }
+ } else {
+ quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) }
+ }
+ })
+ });
+
+ let from_encryptable_impl = inner.iter().flat_map(|field| {
+ get_field_type(field.ty.clone()).map(|field_ty| {
+ let is_option = field_ty.eq("Option");
+ let field_ident = &field.ident;
+ let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
+
+ if is_option || *self == Self::Updated {
+ quote! { #field_ident: map.remove(#field_ident_string) }
+ } else {
+ quote! {
+ #field_ident: map.remove(#field_ident_string).ok_or(
+ error_stack::report!(common_utils::errors::ParsingError::EncodeError(
+ "Unable to convert from HashMap",
+ ))
+ )?
+ }
+ }
+ })
+ });
+
+ quote! {
+ impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st {
+ fn to_encryptable(self) -> FxHashMap<String, #gen3> {
+ let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default());
+ #(#to_encryptable_impl;)*
+ map
+ }
+
+ fn from_encryptable(
+ mut map: FxHashMap<String, Encryptable<#gen2>>,
+ ) -> CustomResult<#gen1, common_utils::errors::ParsingError> {
+ Ok(#gen1 {
+ #(#from_encryptable_impl,)*
+ })
+ }
+ }
+ }
+ }
+}
+
+/// This function generates the temporary struct and ToEncryptable impls for the temporary structs
+fn generate_to_encryptable(
+ struct_name: Ident,
+ fields: Vec<Field>,
+) -> syn::Result<proc_macro2::TokenStream> {
+ let struct_types = [
+ // The first two are to be used as return types we do not need to implement ToEncryptable
+ // on it
+ ("Decrypted", StructType::Decrypted),
+ ("DecryptedUpdate", StructType::DecryptedUpdate),
+ ("FromRequestEncryptable", StructType::FromRequest),
+ ("Encrypted", StructType::Encrypted),
+ ("UpdateEncryptable", StructType::Updated),
+ ];
+
+ let inner_types = get_field_and_inner_types(&fields);
+
+ let inner_type = inner_types.first().map(|(_, ty)| ty).ok_or_else(|| {
+ syn::Error::new(
+ proc_macro2::Span::call_site(),
+ "Please use the macro with attribute #[encrypt] on the fields you want to encrypt",
+ )
+ })?;
+
+ let structs = struct_types.iter().map(|(prefix, struct_type)| {
+ let name = format_ident!("{}{}", prefix, struct_name);
+ let temp_fields = struct_type.generate_struct_fields(&inner_types);
+ quote! {
+ pub struct #name {
+ #(#temp_fields,)*
+ }
+ }
+ });
+
+ // These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs
+ // So skip the first two entries in the list
+ let impls = struct_types
+ .iter()
+ .skip(2)
+ .map(|(prefix, struct_type)| {
+ let name = format_ident!("{}{}", prefix, struct_name);
+
+ let impl_block = if *struct_type != StructType::DecryptedUpdate
+ || *struct_type != StructType::Decrypted
+ {
+ let (gen1, gen2, gen3) = match struct_type {
+ StructType::FromRequest => {
+ let decrypted_name = format_ident!("Decrypted{}", struct_name);
+ (
+ quote! { #decrypted_name },
+ quote! { Secret<#inner_type> },
+ quote! { Secret<#inner_type> },
+ )
+ }
+ StructType::Encrypted => {
+ let decrypted_name = format_ident!("Decrypted{}", struct_name);
+ (
+ quote! { #decrypted_name },
+ quote! { Secret<#inner_type> },
+ quote! { Encryption },
+ )
+ }
+ StructType::Updated => {
+ let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name);
+ (
+ quote! { #decrypted_update_name },
+ quote! { Secret<#inner_type> },
+ quote! { Secret<#inner_type> },
+ )
+ }
+ //Unreachable statement
+ _ => (quote! {}, quote! {}, quote! {}),
+ };
+
+ struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields)
+ } else {
+ quote! {}
+ };
+
+ Ok(quote! {
+ #impl_block
+ })
+ })
+ .collect::<syn::Result<Vec<_>>>()?;
+
+ Ok(quote! {
+ #(#structs)*
+ #(#impls)*
+ })
+}
+
+pub fn derive_to_encryption(
+ input: syn::DeriveInput,
+) -> Result<proc_macro2::TokenStream, syn::Error> {
+ let struct_name = input.ident;
+ let fields = get_encryptable_fields(get_struct_fields(input.data)?);
+
+ generate_to_encryptable(struct_name, fields)
+}
|
2024-10-14T17:27:37Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
This PR adds a macro to generate ToEncryptable trait on different types
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This PR removes the effort of repetitively implementing ToEncryptable trait which is used for batch encryption/decryption in the encryption service by adding a macro which generates code upon deriving it
## How did you test 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 SANDBOX**
- Compiler guided. Since this does not change any core flow
- Basic test of MerchantCreate and Payments for sanity
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
98567569c1c61648eebf0ad7a1ab58bba967b427
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2a53f52f994ca98a31509f05e31b3874b88d15bf
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
19a8474d8731ed7149b541f02ad237e30c4c9f24
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6340
|
Bug: Fix(mandates): handle the connector_mandate creation once and only if the payment is charged
Earlier we used to store the connector mandate id irrespective of the payments status being charged or not for 3DS flows, now we would handle the connector_mandate_id updation in payment_method once and only if the payment has a status as charged.
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 8306deeb258..e36a6d74994 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3356,3 +3356,16 @@ pub enum SurchargeCalculationOverride {
/// Calculate surcharge
Calculate,
}
+
+/// Connector Mandate Status
+#[derive(
+ Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum ConnectorMandateStatus {
+ /// Indicates that the connector mandate is active and can be used for payments.
+ Active,
+ /// Indicates that the connector mandate is not active and hence cannot be used for payments.
+ Inactive,
+}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 277061c78aa..ae98b8a0481 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -12,6 +12,16 @@ use crate::schema::payment_attempt;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_attempt;
+common_utils::impl_to_sql_from_sql_json!(ConnectorMandateReferenceId);
+#[derive(
+ Clone, Debug, serde::Deserialize, serde::Serialize, Eq, PartialEq, diesel::AsExpression,
+)]
+#[diesel(sql_type = diesel::sql_types::Jsonb)]
+pub struct ConnectorMandateReferenceId {
+ pub connector_mandate_id: Option<String>,
+ pub payment_method_id: Option<String>,
+ pub mandate_metadata: Option<serde_json::Value>,
+}
#[cfg(feature = "v2")]
#[derive(
Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable,
@@ -76,6 +86,7 @@ pub struct PaymentAttempt {
pub id: String,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -153,6 +164,7 @@ pub struct PaymentAttempt {
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub connector_transaction_data: Option<String>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -256,6 +268,7 @@ pub struct PaymentAttemptNew {
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -328,6 +341,7 @@ pub struct PaymentAttemptNew {
pub card_network: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -442,6 +456,7 @@ pub enum PaymentAttemptUpdate {
unified_message: Option<Option<String>>,
payment_method_data: Option<serde_json::Value>,
charge_id: Option<String>,
+ connector_mandate_detail: Option<ConnectorMandateReferenceId>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
@@ -757,6 +772,7 @@ pub struct PaymentAttemptUpdateInternal {
customer_acceptance: Option<pii::SecretSerdeValue>,
card_network: Option<String>,
connector_payment_data: Option<String>,
+ connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -813,6 +829,7 @@ pub struct PaymentAttemptUpdateInternal {
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub connector_transaction_data: Option<String>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v2")]
@@ -1002,6 +1019,7 @@ impl PaymentAttemptUpdate {
shipping_cost,
order_tax_amount,
connector_transaction_data,
+ connector_mandate_detail,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -1059,6 +1077,7 @@ impl PaymentAttemptUpdate {
order_tax_amount: order_tax_amount.or(source.order_tax_amount),
connector_transaction_data: connector_transaction_data
.or(source.connector_transaction_data),
+ connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail),
..source
}
}
@@ -2054,6 +2073,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -2109,6 +2129,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -2194,6 +2215,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost,
order_tax_amount,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -2250,6 +2272,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -2307,6 +2330,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -2364,6 +2388,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -2419,6 +2444,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -2441,6 +2467,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_message,
payment_method_data,
charge_id,
+ connector_mandate_detail,
} => {
let (connector_transaction_id, connector_transaction_data) =
connector_transaction_id
@@ -2498,6 +2525,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail,
}
}
PaymentAttemptUpdate::ErrorUpdate {
@@ -2570,6 +2598,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail: None,
}
}
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
@@ -2623,6 +2652,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -2684,6 +2714,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -2752,6 +2783,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail: None,
}
}
PaymentAttemptUpdate::PreprocessingUpdate {
@@ -2819,6 +2851,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail: None,
}
}
PaymentAttemptUpdate::CaptureUpdate {
@@ -2876,6 +2909,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -2932,6 +2966,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -2997,6 +3032,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail: None,
}
}
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
@@ -3053,6 +3089,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -3111,6 +3148,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -3178,6 +3216,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
card_network: None,
shipping_cost: None,
order_tax_amount: None,
+ connector_mandate_detail: None,
}
}
PaymentAttemptUpdate::PostSessionTokensUpdate {
@@ -3234,6 +3273,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data: None,
+ connector_mandate_detail: None,
},
}
}
@@ -3319,7 +3359,6 @@ mod tests {
"user_agent": "amet irure esse"
}
},
- "mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 5cd2abd3599..8d2dfc47b62 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -850,6 +850,7 @@ diesel::table! {
order_tax_amount -> Nullable<Int8>,
#[max_length = 512]
connector_transaction_data -> Nullable<Varchar>,
+ connector_mandate_detail -> Nullable<Jsonb>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index d662603981b..45a4ce03e55 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -821,6 +821,7 @@ diesel::table! {
id -> Varchar,
shipping_cost -> Nullable<Int8>,
order_tax_amount -> Nullable<Int8>,
+ connector_mandate_detail -> Nullable<Jsonb>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index db30d02bd7c..88617afb392 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -12,7 +12,7 @@ use crate::schema::payment_attempt;
use crate::schema_v2::payment_attempt;
use crate::{
enums::{MandateDataType, MandateDetails},
- PaymentAttemptNew,
+ ConnectorMandateReferenceId, PaymentAttemptNew,
};
#[cfg(feature = "v2")]
@@ -204,6 +204,7 @@ pub struct PaymentAttemptBatchNew {
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub connector_transaction_data: Option<String>,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -282,6 +283,7 @@ impl PaymentAttemptBatchNew {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
order_tax_amount: self.order_tax_amount,
+ connector_mandate_detail: self.connector_mandate_detail,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 691037c2824..8ecac77e54e 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -10,7 +10,8 @@ use common_utils::{
},
};
use diesel_models::{
- PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew,
+ ConnectorMandateReferenceId, PaymentAttempt as DieselPaymentAttempt,
+ PaymentAttemptNew as DieselPaymentAttemptNew,
PaymentAttemptUpdate as DieselPaymentAttemptUpdate,
};
use error_stack::ResultExt;
@@ -222,6 +223,7 @@ pub struct PaymentAttempt {
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub id: String,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
impl PaymentAttempt {
@@ -331,6 +333,7 @@ pub struct PaymentAttempt {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)]
@@ -624,6 +627,7 @@ pub struct PaymentAttemptNew {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
+ pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
@@ -732,6 +736,7 @@ pub enum PaymentAttemptUpdate {
unified_message: Option<Option<String>>,
payment_method_data: Option<serde_json::Value>,
charge_id: Option<String>,
+ connector_mandate_detail: Option<ConnectorMandateReferenceId>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
@@ -992,6 +997,7 @@ impl PaymentAttemptUpdate {
unified_message,
payment_method_data,
charge_id,
+ connector_mandate_detail,
} => DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
@@ -1013,6 +1019,7 @@ impl PaymentAttemptUpdate {
unified_message,
payment_method_data,
charge_id,
+ connector_mandate_detail,
},
Self::UnresolvedResponseUpdate {
status,
@@ -1281,6 +1288,7 @@ impl behaviour::Conversion for PaymentAttempt {
connector_transaction_data,
order_tax_amount: self.net_amount.get_order_tax_amount(),
shipping_cost: self.net_amount.get_shipping_cost(),
+ connector_mandate_detail: self.connector_mandate_detail,
})
}
@@ -1361,6 +1369,7 @@ impl behaviour::Conversion for PaymentAttempt {
customer_acceptance: storage_model.customer_acceptance,
profile_id: storage_model.profile_id,
organization_id: storage_model.organization_id,
+ connector_mandate_detail: storage_model.connector_mandate_detail,
})
}
.await
@@ -1442,6 +1451,7 @@ impl behaviour::Conversion for PaymentAttempt {
card_network,
order_tax_amount: self.net_amount.get_order_tax_amount(),
shipping_cost: self.net_amount.get_shipping_cost(),
+ connector_mandate_detail: self.connector_mandate_detail,
})
}
}
@@ -1517,6 +1527,7 @@ impl behaviour::Conversion for PaymentAttempt {
shipping_cost,
order_tax_amount,
connector,
+ connector_mandate_detail,
} = self;
let (connector_payment_id, connector_payment_data) = connector_payment_id
@@ -1580,6 +1591,7 @@ impl behaviour::Conversion for PaymentAttempt {
external_reference_id,
connector,
connector_payment_data,
+ connector_mandate_detail,
})
}
@@ -1651,6 +1663,7 @@ impl behaviour::Conversion for PaymentAttempt {
authentication_applied: storage_model.authentication_applied,
external_reference_id: storage_model.external_reference_id,
connector: storage_model.connector,
+ connector_mandate_detail: storage_model.connector_mandate_detail,
})
}
.await
@@ -1718,6 +1731,7 @@ impl behaviour::Conversion for PaymentAttempt {
order_tax_amount: self.order_tax_amount,
shipping_cost: self.shipping_cost,
amount_to_capture: self.amount_to_capture,
+ connector_mandate_detail: self.connector_mandate_detail,
})
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 7c97516192e..27d73d0df46 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4071,6 +4071,7 @@ impl AttemptType {
customer_acceptance: old_payment_attempt.customer_acceptance,
organization_id: old_payment_attempt.organization_id,
profile_id: old_payment_attempt.profile_id,
+ connector_mandate_detail: None,
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 9ec2438ddb3..ca32be35e55 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -614,7 +614,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
} else {
(None, payment_method_info)
};
-
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data.map(|mut sm| {
sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 779b2d29c06..fc1f71c2085 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1206,8 +1206,10 @@ impl PaymentCreate {
.map(Secret::new),
organization_id: organization_id.clone(),
profile_id,
+ connector_mandate_detail: None,
},
additional_pm_data,
+
))
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6ead0523020..3bb6647b527 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1,11 +1,12 @@
use std::collections::HashMap;
+use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
use common_enums::{AuthorizationStatus, SessionUpdateStatus};
use common_utils::{
- ext_traits::{AsyncExt, Encode},
+ ext_traits::{AsyncExt, Encode, ValueExt},
types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},
};
use error_stack::{report, ResultExt};
@@ -184,14 +185,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
let save_payment_call_future = Box::pin(tokenization::save_payment_method(
state,
connector_name.clone(),
- merchant_connector_id.clone(),
save_payment_data,
customer_id.clone(),
merchant_account,
resp.request.payment_method_type,
key_store,
- Some(resp.request.amount),
- Some(resp.request.currency),
billing_name.clone(),
payment_method_billing_address,
business_profile,
@@ -208,7 +206,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
resp.request.setup_future_usage,
Some(enums::FutureUsage::OffSession)
);
-
+ let storage_scheme = merchant_account.storage_scheme;
if is_legacy_mandate {
// Mandate is created on the application side and at the connector.
let tokenization::SavePaymentMethodDataResponse {
@@ -233,15 +231,46 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
// The mandate is created on connector's end.
let tokenization::SavePaymentMethodDataResponse {
payment_method_id,
- mandate_reference_id,
+ connector_mandate_reference_id,
..
} = save_payment_call_future.await?;
-
+ payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id {
+ match state
+ .store
+ .find_payment_method(
+ &(state.into()),
+ key_store,
+ payment_method_id,
+ storage_scheme,
+ )
+ .await
+ {
+ Ok(payment_method) => Some(payment_method),
+ Err(error) => {
+ if error.current_context().is_db_not_found() {
+ logger::info!("Payment Method not found in db {:?}", error);
+ None
+ } else {
+ Err(error)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error retrieving payment method from db")
+ .map_err(|err| logger::error!(payment_method_retrieve=?err))
+ .ok()
+ }
+ }
+ }
+ } else {
+ None
+ };
payment_data.payment_attempt.payment_method_id = payment_method_id;
-
+ payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
+ .clone()
+ .map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
- mandate_reference_id,
+ mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
+ MandateReferenceId::ConnectorMandateId(connector_mandate_id)
+ }),
});
Ok(())
} else if should_avoid_saving {
@@ -256,16 +285,10 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
let key_store = key_store.clone();
let state = state.clone();
let customer_id = payment_data.payment_intent.customer_id.clone();
-
- let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let payment_attempt = payment_data.payment_attempt.clone();
let business_profile = business_profile.clone();
-
- let amount = resp.request.amount;
- let currency = resp.request.currency;
let payment_method_type = resp.request.payment_method_type;
- let storage_scheme = merchant_account.clone().storage_scheme;
let payment_method_billing_address = payment_method_billing_address.cloned();
logger::info!("Call to save_payment_method in locker");
@@ -276,14 +299,11 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
let result = Box::pin(tokenization::save_payment_method(
&state,
connector_name,
- merchant_connector_id,
save_payment_data,
customer_id,
&merchant_account,
payment_method_type,
&key_store,
- Some(amount),
- Some(currency),
billing_name,
payment_method_billing_address.as_ref(),
&business_profile,
@@ -554,6 +574,33 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
where
F: 'b + Clone + Send + Sync,
{
+ let (connector_mandate_id, mandate_metadata) = resp
+ .response
+ .clone()
+ .ok()
+ .and_then(|resp| {
+ if let types::PaymentsResponseData::TransactionResponse {
+ mandate_reference, ..
+ } = resp
+ {
+ mandate_reference.map(|mandate_ref| {
+ (
+ mandate_ref.connector_mandate_id.clone(),
+ mandate_ref.mandate_metadata.clone(),
+ )
+ })
+ } else {
+ None
+ }
+ })
+ .unwrap_or((None, None));
+
+ update_connector_mandate_details_for_the_flow(
+ connector_mandate_id,
+ mandate_metadata,
+ payment_data,
+ )?;
+
update_payment_method_status_and_ntid(
state,
key_store,
@@ -1038,19 +1085,16 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let tokenization::SavePaymentMethodDataResponse {
payment_method_id,
- mandate_reference_id,
+ connector_mandate_reference_id,
..
} = Box::pin(tokenization::save_payment_method(
state,
connector_name,
- merchant_connector_id.clone(),
save_payment_data,
customer_id.clone(),
merchant_account,
resp.request.payment_method_type,
key_store,
- resp.request.amount,
- Some(resp.request.currency),
billing_name,
None,
business_profile,
@@ -1069,9 +1113,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa
.await?;
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.mandate_id = mandate_id;
+ payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
+ .clone()
+ .map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
- mandate_reference_id,
+ mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
+ MandateReferenceId::ConnectorMandateId(connector_mandate_id)
+ }),
});
Ok(())
}
@@ -1127,6 +1176,32 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData
where
F: 'b + Clone + Send + Sync,
{
+ let (connector_mandate_id, mandate_metadata) = resp
+ .response
+ .clone()
+ .ok()
+ .and_then(|resp| {
+ if let types::PaymentsResponseData::TransactionResponse {
+ mandate_reference, ..
+ } = resp
+ {
+ mandate_reference.map(|mandate_ref| {
+ (
+ mandate_ref.connector_mandate_id.clone(),
+ mandate_ref.mandate_metadata.clone(),
+ )
+ })
+ } else {
+ None
+ }
+ })
+ .unwrap_or((None, None));
+ update_connector_mandate_details_for_the_flow(
+ connector_mandate_id,
+ mandate_metadata,
+ payment_data,
+ )?;
+
update_payment_method_status_and_ntid(
state,
key_store,
@@ -1487,6 +1562,78 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.payment_intent
.fingerprint_id
.clone_from(&payment_data.payment_attempt.fingerprint_id);
+
+ if let Some(payment_method) =
+ payment_data.payment_method_info.clone()
+ {
+ // Parse value to check for mandates' existence
+ let mandate_details = payment_method
+ .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 ",
+ )?;
+
+ if let Some(mca_id) =
+ payment_data.payment_attempt.merchant_connector_id.clone()
+ {
+ // check if the mandate has not already been set to active
+ if !mandate_details
+ .as_ref()
+ .map(|payment_mandate_reference| {
+
+ payment_mandate_reference.0.get(&mca_id)
+ .map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))
+ .unwrap_or(false)
+ })
+ .unwrap_or(false)
+ {
+ let (connector_mandate_id, mandate_metadata) = payment_data.payment_attempt.connector_mandate_detail.clone()
+ .map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata))
+ .unwrap_or((None, None));
+
+ // Update the connector mandate details with the payment attempt connector mandate id
+ let connector_mandate_details =
+ tokenization::update_connector_mandate_details(
+ mandate_details,
+ payment_data.payment_attempt.payment_method_type,
+ Some(
+ payment_data
+ .payment_attempt
+ .net_amount
+ .get_total_amount()
+ .get_amount_as_i64(),
+ ),
+ payment_data.payment_attempt.currency,
+ payment_data.payment_attempt.merchant_connector_id.clone(),
+ connector_mandate_id,
+ mandate_metadata,
+ )?;
+ // Update the payment method table with the active mandate record
+ payment_methods::cards::update_payment_method_connector_mandate_details(
+ state,
+ key_store,
+ &*state.store,
+ payment_method,
+ connector_mandate_details,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+ }
+ }
+ }
+
metrics::SUCCESSFUL_PAYMENT.add(&metrics::CONTEXT, 1, &[]);
}
@@ -1561,6 +1708,10 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
encoded_data,
payment_method_data: additional_payment_method_data,
charge_id,
+ connector_mandate_detail: payment_data
+ .payment_attempt
+ .connector_mandate_detail
+ .clone(),
}),
),
};
@@ -1760,59 +1911,6 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.in_current_span(),
);
- // When connector requires redirection for mandate creation it can update the connector mandate_id in payment_methods during Psync and CompleteAuthorize
-
- let flow_name = core_utils::get_flow_name::<F>()?;
- if flow_name == "PSync" || flow_name == "CompleteAuthorize" {
- 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.mandate_metadata.clone(),
- )
- } else {
- (None, None)
- }
- }
- _ => (None, None),
- },
- Err(_) => (None, None),
- };
- if let Some(payment_method) = payment_data.payment_method_info.clone() {
- let connector_mandate_details =
- tokenization::update_connector_mandate_details_in_payment_method(
- payment_method.clone(),
- payment_method.payment_method_type,
- Some(
- payment_data
- .payment_attempt
- .net_amount
- .get_total_amount()
- .get_amount_as_i64(),
- ),
- 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,
- key_store,
- &*state.store,
- payment_method.clone(),
- connector_mandate_details,
- storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to update payment method in db")?
- }
- }
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
let m_router_data_merchant_id = router_data.merchant_id.clone();
@@ -2032,6 +2130,35 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
Ok(())
}
+fn update_connector_mandate_details_for_the_flow<F: Clone>(
+ connector_mandate_id: Option<String>,
+ mandate_metadata: Option<serde_json::Value>,
+ payment_data: &mut PaymentData<F>,
+) -> RouterResult<()> {
+ let connector_mandate_reference_id = if connector_mandate_id.is_some() {
+ Some(ConnectorMandateReferenceId {
+ connector_mandate_id: connector_mandate_id.clone(),
+ payment_method_id: None,
+ update_history: None,
+ mandate_metadata: mandate_metadata.clone(),
+ })
+ } else {
+ None
+ };
+
+ payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
+ .clone()
+ .map(ForeignFrom::foreign_from);
+
+ payment_data.set_mandate_id(api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
+ MandateReferenceId::ConnectorMandateId(connector_mandate_id)
+ }),
+ });
+ Ok(())
+}
+
fn response_to_capture_update(
multiple_capture_data: &MultipleCaptureData,
response_list: HashMap<String, CaptureSyncResponse>,
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 374c5680685..e4b6d0e287c 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -456,6 +456,7 @@ where
unified_message: None,
payment_method_data: additional_payment_method_data,
charge_id,
+ connector_mandate_detail: None,
};
#[cfg(feature = "v1")]
@@ -642,6 +643,7 @@ pub fn make_new_payment_attempt(
fingerprint_id: Default::default(),
charge_id: Default::default(),
customer_acceptance: Default::default(),
+ connector_mandate_detail: Default::default(),
}
}
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 213a9211c06..b4e5ade5698 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -5,8 +5,8 @@ use std::collections::HashMap;
not(feature = "payment_methods_v2")
))]
use api_models::payment_methods::PaymentMethodsData;
-use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
-use common_enums::PaymentMethod;
+use api_models::payments::ConnectorMandateReferenceId;
+use common_enums::{ConnectorMandateStatus, PaymentMethod};
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, Encode, ValueExt},
@@ -61,7 +61,7 @@ impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>
pub struct SavePaymentMethodDataResponse {
pub payment_method_id: Option<String>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
- pub mandate_reference_id: Option<MandateReferenceId>,
+ pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
@@ -72,14 +72,11 @@ pub struct SavePaymentMethodDataResponse {
pub async fn save_payment_method<FData>(
state: &SessionState,
connector_name: String,
- merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
save_payment_method_data: SavePaymentMethodData<FData>,
customer_id: Option<id_type::CustomerId>,
merchant_account: &domain::MerchantAccount,
payment_method_type: Option<storage_enums::PaymentMethodType>,
key_store: &domain::MerchantKeyStore,
- amount: Option<i64>,
- currency: Option<storage_enums::Currency>,
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&api::Address>,
business_profile: &domain::Profile,
@@ -174,32 +171,6 @@ where
}
_ => (None, None),
};
- let check_for_mit_mandates = save_payment_method_data
- .request
- .get_setup_mandate_details()
- .is_none()
- && save_payment_method_data
- .request
- .get_setup_future_usage()
- .map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession)
- .unwrap_or(false);
- // insert in PaymentMethods if its a off-session mit payment
- let connector_mandate_details = if check_for_mit_mandates {
- add_connector_mandate_details_in_payment_method(
- payment_method_type,
- amount,
- currency,
- merchant_connector_id.clone(),
- connector_mandate_id.clone(),
- mandate_metadata.clone(),
- )
- } else {
- None
- }
- .map(|connector_mandate_data| connector_mandate_data.encode_to_value())
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to serialize customer acceptance to value")?;
let pm_id = if customer_acceptance.is_some() {
let payment_method_create_request =
@@ -384,24 +355,6 @@ where
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
- if check_for_mit_mandates {
- let connector_mandate_details =
- update_connector_mandate_details_in_payment_method(
- pm.clone(),
- payment_method_type,
- amount,
- currency,
- merchant_connector_id.clone(),
- connector_mandate_id.clone(),
- mandate_metadata.clone(),
- )?;
-
- payment_methods::cards::update_payment_method_connector_mandate_details(state,
- key_store,db, pm, connector_mandate_details, merchant_account.storage_scheme).await.change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable("Failed to update payment method in db")?;
- }
}
Err(err) => {
if err.current_context().is_db_not_found() {
@@ -418,7 +371,7 @@ where
customer_acceptance,
pm_data_encrypted.map(Into::into),
key_store,
- connector_mandate_details,
+ None,
pm_status,
network_transaction_id,
merchant_account.storage_scheme,
@@ -489,28 +442,7 @@ where
resp.payment_method_id = payment_method_id;
let existing_pm = match payment_method {
- Ok(pm) => {
- // update if its a off-session mit payment
- if check_for_mit_mandates {
- let connector_mandate_details =
- update_connector_mandate_details_in_payment_method(
- pm.clone(),
- payment_method_type,
- amount,
- currency,
- merchant_connector_id.clone(),
- connector_mandate_id.clone(),
- mandate_metadata.clone(),
- )?;
-
- payment_methods::cards::update_payment_method_connector_mandate_details( state,
- key_store,db, pm.clone(), connector_mandate_details, merchant_account.storage_scheme).await.change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable("Failed to update payment method in db")?;
- }
- Ok(pm)
- }
+ Ok(pm) => Ok(pm),
Err(err) => {
if err.current_context().is_db_not_found() {
payment_methods::cards::create_payment_method(
@@ -524,7 +456,7 @@ where
customer_acceptance,
pm_data_encrypted.map(Into::into),
key_store,
- connector_mandate_details,
+ None,
pm_status,
network_transaction_id,
merchant_account.storage_scheme,
@@ -733,7 +665,7 @@ where
customer_acceptance,
pm_data_encrypted.map(Into::into),
key_store,
- connector_mandate_details,
+ None,
pm_status,
network_transaction_id,
merchant_account.storage_scheme,
@@ -755,35 +687,28 @@ where
} else {
None
};
- let cmid_config = db
- .find_config_by_key_unwrap_or(
- format!("{}_should_show_connector_mandate_id_in_payments_response", merchant_account.get_id().get_string_repr().to_owned()).as_str(),
- Some("false".to_string()),
- )
- .await.map_err(|err| services::logger::error!(message="Failed to fetch the config", connector_mandate_details_population=?err)).ok();
-
- let mandate_reference_id = match cmid_config {
- Some(config) if config.config == "true" => Some(
- MandateReferenceId::ConnectorMandateId(ConnectorMandateReferenceId {
- connector_mandate_id: connector_mandate_id.clone(),
- payment_method_id: pm_id.clone(),
- update_history: None,
- mandate_metadata: mandate_metadata.clone(),
- }),
- ),
- _ => None,
+ // check if there needs to be a config if yes then remove it to a different place
+ let connector_mandate_reference_id = if connector_mandate_id.is_some() {
+ Some(ConnectorMandateReferenceId {
+ connector_mandate_id: connector_mandate_id.clone(),
+ payment_method_id: None,
+ update_history: None,
+ mandate_metadata: mandate_metadata.clone(),
+ })
+ } else {
+ None
};
Ok(SavePaymentMethodDataResponse {
payment_method_id: pm_id,
payment_method_status: pm_status,
- mandate_reference_id,
+ connector_mandate_reference_id,
})
}
Err(_) => Ok(SavePaymentMethodDataResponse {
payment_method_id: None,
payment_method_status: None,
- mandate_reference_id: None,
+ connector_mandate_reference_id: None,
}),
}
}
@@ -795,14 +720,11 @@ where
pub async fn save_payment_method<FData>(
_state: &SessionState,
_connector_name: String,
- _merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
_save_payment_method_data: SavePaymentMethodData<FData>,
_customer_id: Option<id_type::CustomerId>,
_merchant_account: &domain::MerchantAccount,
_payment_method_type: Option<storage_enums::PaymentMethodType>,
_key_store: &domain::MerchantKeyStore,
- _amount: Option<i64>,
- _currency: Option<storage_enums::Currency>,
_billing_name: Option<Secret<String>>,
_payment_method_billing_address: Option<&api::Address>,
_business_profile: &domain::Profile,
@@ -1226,6 +1148,7 @@ pub fn add_connector_mandate_details_in_payment_method(
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata,
+ connector_mandate_status: Some(ConnectorMandateStatus::Active),
},
);
Some(storage::PaymentsMandateReference(mandate_details))
@@ -1234,8 +1157,8 @@ pub fn add_connector_mandate_details_in_payment_method(
}
}
-pub fn update_connector_mandate_details_in_payment_method(
- payment_method: domain::PaymentMethod,
+pub fn update_connector_mandate_details(
+ mandate_details: Option<storage::PaymentsMandateReference>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
@@ -1243,17 +1166,8 @@ pub fn update_connector_mandate_details_in_payment_method(
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(_) => {
- let mandate_details = payment_method
- .connector_mandate_details
- .map(|val| {
- val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference")
- })
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
-
+ let mandate_reference = match mandate_details {
+ Some(mut payment_mandate_reference) => {
if let Some((mca_id, connector_mandate_id)) =
merchant_connector_id.clone().zip(connector_mandate_id)
{
@@ -1263,20 +1177,21 @@ pub fn update_connector_mandate_details_in_payment_method(
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata: mandate_metadata.clone(),
+ connector_mandate_status: Some(ConnectorMandateStatus::Active),
};
- mandate_details.map(|mut payment_mandate_reference| {
- payment_mandate_reference
- .entry(mca_id)
- .and_modify(|pm| *pm = updated_record)
- .or_insert(storage::PaymentsMandateReferenceRecord {
- connector_mandate_id,
- payment_method_type,
- original_payment_authorized_amount: authorized_amount,
- original_payment_authorized_currency: authorized_currency,
- mandate_metadata: mandate_metadata.clone(),
- });
- payment_mandate_reference
- })
+
+ payment_mandate_reference
+ .entry(mca_id)
+ .and_modify(|pm| *pm = updated_record)
+ .or_insert(storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id,
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ mandate_metadata: mandate_metadata.clone(),
+ connector_mandate_status: Some(ConnectorMandateStatus::Active),
+ });
+ Some(payment_mandate_reference)
} else {
None
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 36586fdb155..0d9d684cae8 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1,8 +1,8 @@
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
use api_models::payments::{
- Address, CustomerDetails, CustomerDetailsResponse, FrmMessage, PaymentChargeRequest,
- PaymentChargeResponse, RequestSurchargeDetails,
+ Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,
+ PaymentChargeRequest, PaymentChargeResponse, RequestSurchargeDetails,
};
use common_enums::{Currency, RequestIncrementalAuthorization};
use common_utils::{
@@ -11,7 +11,10 @@ use common_utils::{
pii::Email,
types::{self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnitForConnector},
};
-use diesel_models::ephemeral_key;
+use diesel_models::{
+ ephemeral_key,
+ payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,
+};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
use masking::{ExposeInterface, Maskable, PeekInterface, Secret};
@@ -2849,3 +2852,23 @@ impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration>
}
}
}
+
+impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId {
+ fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self {
+ Self {
+ connector_mandate_id: value.connector_mandate_id,
+ payment_method_id: value.payment_method_id,
+ update_history: None,
+ mandate_metadata: value.mandate_metadata,
+ }
+ }
+}
+impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId {
+ fn foreign_from(value: ConnectorMandateReferenceId) -> Self {
+ Self {
+ connector_mandate_id: value.connector_mandate_id,
+ payment_method_id: value.payment_method_id,
+ mandate_metadata: value.mandate_metadata,
+ }
+ }
+}
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 3942c395665..19670fc8ccb 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -259,13 +259,13 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
let merchant_connector_account = match merchant_connector_account {
Some(merchant_connector_account) => merchant_connector_account,
None => {
- helper_utils::get_mca_from_object_reference_id(
+ Box::pin(helper_utils::get_mca_from_object_reference_id(
&state,
object_ref_id.clone(),
&merchant_account,
&connector_name,
&key_store,
- )
+ ))
.await?
}
};
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 40335d5f2ab..502e03b7293 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -216,6 +216,7 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ connector_mandate_detail: Default::default(),
};
let store = state
@@ -299,6 +300,7 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ connector_mandate_detail: Default::default(),
};
let store = state
.stores
@@ -395,6 +397,7 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ connector_mandate_detail: Default::default(),
};
let store = state
.stores
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index bb1b801edb6..20d0ee74b01 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -125,6 +125,7 @@ pub struct PaymentsMandateReferenceRecord {
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::Currency>,
pub mandate_metadata: Option<serde_json::Value>,
+ pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 122989a82cf..7faafb14ec1 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -339,6 +339,7 @@ pub async fn generate_sample_data(
shipping_cost: None,
order_tax_amount: None,
connector_transaction_data,
+ connector_mandate_detail: None,
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 59fb1155480..121397cdfb9 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -180,6 +180,7 @@ impl PaymentAttemptInterface for MockDb {
customer_acceptance: payment_attempt.customer_acceptance,
organization_id: payment_attempt.organization_id,
profile_id: payment_attempt.profile_id,
+ connector_mandate_detail: payment_attempt.connector_mandate_detail,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 024ab9fd814..5087e28b854 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -531,6 +531,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
customer_acceptance: payment_attempt.customer_acceptance.clone(),
organization_id: payment_attempt.organization_id.clone(),
profile_id: payment_attempt.profile_id.clone(),
+ connector_mandate_detail: payment_attempt.connector_mandate_detail.clone(),
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -1453,6 +1454,7 @@ impl DataModelExt for PaymentAttempt {
connector_transaction_data,
shipping_cost: self.net_amount.get_shipping_cost(),
order_tax_amount: self.net_amount.get_order_tax_amount(),
+ connector_mandate_detail: self.connector_mandate_detail,
}
}
@@ -1528,6 +1530,7 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
+ connector_mandate_detail: storage_model.connector_mandate_detail,
}
}
}
@@ -1610,6 +1613,7 @@ impl DataModelExt for PaymentAttemptNew {
profile_id: self.profile_id,
shipping_cost: self.net_amount.get_shipping_cost(),
order_tax_amount: self.net_amount.get_order_tax_amount(),
+ connector_mandate_detail: self.connector_mandate_detail,
}
}
@@ -1681,6 +1685,7 @@ impl DataModelExt for PaymentAttemptNew {
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
+ connector_mandate_detail: storage_model.connector_mandate_detail,
}
}
}
diff --git a/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql
new file mode 100644
index 00000000000..f4e6f2e2e26
--- /dev/null
+++ b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE
+ payment_attempt DROP COLUMN connector_mandate_detail;
\ No newline at end of file
diff --git a/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql
new file mode 100644
index 00000000000..bb592f623d4
--- /dev/null
+++ b/migrations/2024-10-13-182546_add_connector_mandate_id_in_payment_attempt/up.sql
@@ -0,0 +1,5 @@
+-- Your SQL goes here
+ALTER TABLE
+ payment_attempt
+ADD
+ COLUMN connector_mandate_detail JSONB DEFAULT NULL;
\ No newline at end of file
|
2024-10-15T17:41:53Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Earlier we used to store the connector mandate id irrespective of the payments status being charged or not for 3DS flows, now we would handle the connector_mandate_id updation in payment_method once and only if the payment has a status as charged.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Configure a MA and a MCA
- Make a 3ds mandate failed payment, it would be populated in the payment_attempt, but not in the payment_method table
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \
--data-raw '{
"amount": 8500,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"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"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
```
Confirm
curl --location 'http://localhost:8080/payments/pay_v7bENZR0bgPe0g6ThobF/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: pk_dev_07feea3d36ed4f8da3cd844b07b8e3e9' \
--data '{
"confirm": true,
"client_secret":"pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"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"
},
"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_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4000008400001629",
"card_exp_month": "06",
"card_exp_year": "2030",
"card_holder_name": "John T",
"card_cvc": "737"
}
}
}'
```
```
Response
{
"payment_id": "pay_v7bENZR0bgPe0g6ThobF",
"merchant_id": "merchant_1729155606",
"status": "requires_customer_action",
"amount": 8500,
"net_amount": 8500,
"amount_capturable": 8500,
"amount_received": 0,
"connector": "stripe",
"client_secret": "pay_v7bENZR0bgPe0g6ThobF_secret_d792ajlpJ4z6XlS9esjK",
"created": "2024-10-17T09:01:29.364Z",
"currency": "USD",
"customer_id": "CustomerX777",
"customer": {
"id": "CustomerX777",
"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": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1629",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": null,
"card_exp_month": "06",
"card_exp_year": "2030",
"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": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_v7bENZR0bgPe0g6ThobF/merchant_1729155606/pay_v7bENZR0bgPe0g6ThobF_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "pi_3QApaRD5R7gDAGff0khxOUA8",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pi_3QApaRD5R7gDAGff0khxOUA8",
"payment_link": null,
"profile_id": "pro_OYE7Iv9nauJb3HXYFB1u",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-17T09:16:29.364Z",
"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_PxUXcAinbE62hBE1mAg2",
"payment_method_status": "inactive",
"updated": "2024-10-17T09:01:39.749Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": "pm_1QApaRD5R7gDAGffKM5cG6sU"
}
```
```
The payment_method_table won't have connectir_mandate_details
```
<img width="1725" alt="Screenshot 2024-10-17 at 2 48 01 PM" src="https://github.com/user-attachments/assets/c361f388-0c64-4b57-b5ff-ae8b4d5a3881">
- Make a 3ds payment successful, then only it will be populated in the payment_method
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \
--data-raw '{
"amount": 8500,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"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"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
```
Confirm
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-feature: router-custom' \
--header 'api-key: dev_5SpseUd7WAhIwgQeMpoCKwEeaPjmduquAv3Qu4VxdRkSBkilsq5arTZa6nXoPokw' \
--data-raw '{
"amount": 8500,
"currency": "USD",
"confirm": false,
"customer_id": "CustomerX777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"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"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
```
response
{
"payment_id": "pay_m59xmko152RMgzTqgUeP",
"merchant_id": "merchant_1729155606",
"status": "succeeded",
"amount": 8500,
"net_amount": 8500,
"amount_capturable": 0,
"amount_received": 8500,
"connector": "stripe",
"client_secret": "pay_m59xmko152RMgzTqgUeP_secret_m8J1xt82aJYVaK4o4vNs",
"created": "2024-10-17T09:18:18.049Z",
"currency": "USD",
"customer_id": "CustomerX777",
"customer": {
"id": "CustomerX777",
"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": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "06",
"card_exp_year": "2030",
"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": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "debit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3QApqiD5R7gDAGff1ykvxYD0",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pi_3QApqiD5R7gDAGff1ykvxYD0",
"payment_link": null,
"profile_id": "pro_OYE7Iv9nauJb3HXYFB1u",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_LKJi6vdC2IEQwbEaVJQP",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-10-17T09:33:18.049Z",
"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_9ahIWQWjvWNTYCi1myPc",
"payment_method_status": "active",
"updated": "2024-10-17T09:18:35.865Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
The payment_method would have a connector_mandate_id with it
<img width="1725" alt="Screenshot 2024-10-17 at 2 54 03 PM" src="https://github.com/user-attachments/assets/847ad97b-2cd0-4f48-a00f-8b833967df37">
- If another CIT mandate payment is made it wouldn't be populated anymore
- Make a complete authorise mandate payment , it should be saved in the payment_method, for that mca_id
- Make a external 3ds mandate payment , it should be saved in the payment_method, for that mca_id
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
962afbd084458e9afb11a0278a8210edd9226a3d
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
19a8474d8731ed7149b541f02ad237e30c4c9f24
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6330
|
Bug: fix(list): improve querying time for payments list
Quick Fix.
Currently payment list is giving intermittent 5xx. After analyzing logs we got to knwo that it is happening for the count query
That query need to be called always and we can skip this in most of the cases.
Also add the logs around count.
This can be a temporary help, till will move to more durable solution.
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 674a19f3ef8..039c99ef348 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4449,6 +4449,17 @@ pub struct PaymentListFilterConstraints {
/// The List of all the card networks to filter payments list
pub card_network: Option<Vec<enums::CardNetwork>>,
}
+
+impl PaymentListFilterConstraints {
+ pub fn has_no_attempt_filters(&self) -> bool {
+ self.connector.is_none()
+ && self.payment_method.is_none()
+ && self.payment_method_type.is_none()
+ && self.authentication_type.is_none()
+ && self.merchant_connector_id.is_none()
+ }
+}
+
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentListFilters {
/// The list of available connector filters
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 67af7a3bef5..85c69824892 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>>,
- profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
let mut filter = <Self as HasTable>::table()
@@ -394,17 +393,23 @@ impl PaymentAttempt {
if let Some(merchant_connector_id) = merchant_connector_id {
filter = filter.filter(dsl::merchant_connector_id.eq_any(merchant_connector_id))
}
- if let Some(profile_id_list) = profile_id_list {
- filter = filter.filter(dsl::profile_id.eq_any(profile_id_list))
- }
+
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
- db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
+ // TODO: Remove these logs after debugging the issue for delay in count query
+ let start_time = std::time::Instant::now();
+ router_env::logger::debug!("Executing count query start_time: {:?}", start_time);
+ let result = db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_result_async::<i64>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.change_context(DatabaseError::Others)
- .attach_printable("Error filtering count of payments")
+ .attach_printable("Error filtering count of payments");
+
+ let duration = start_time.elapsed();
+ router_env::logger::debug!("Completed count query in {:?}", duration);
+
+ result
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 5aba0616143..ea65cfff8b4 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -158,7 +158,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>>,
- 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 68f318958a2..651a79a0c14 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3737,54 +3737,69 @@ pub async fn apply_filters_on_payments(
merchant_key_store: domain::MerchantKeyStore,
constraints: api::PaymentListFilterConstraints,
) -> RouterResponse<api::PaymentListResponseV2> {
- let limit = &constraints.limit;
- helpers::validate_payment_list_request_for_joins(*limit)?;
- let db: &dyn StorageInterface = state.store.as_ref();
- let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?;
- let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
- .get_filtered_payment_intents_attempt(
- &(&state).into(),
- merchant.get_id(),
- &pi_fetch_constraints,
- &merchant_key_store,
- merchant.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
- let data: Vec<api::PaymentsResponse> =
- list.into_iter().map(ForeignFrom::foreign_from).collect();
-
- let active_attempt_ids = db
- .get_filtered_active_attempt_ids_for_total_count(
- merchant.get_id(),
- &pi_fetch_constraints,
- merchant.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+ common_utils::metrics::utils::record_operation_time(
+ async {
+ let limit = &constraints.limit;
+ helpers::validate_payment_list_request_for_joins(*limit)?;
+ let db: &dyn StorageInterface = state.store.as_ref();
+ let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?;
+ let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
+ .get_filtered_payment_intents_attempt(
+ &(&state).into(),
+ merchant.get_id(),
+ &pi_fetch_constraints,
+ &merchant_key_store,
+ merchant.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let data: Vec<api::PaymentsResponse> =
+ list.into_iter().map(ForeignFrom::foreign_from).collect();
+
+ let active_attempt_ids = db
+ .get_filtered_active_attempt_ids_for_total_count(
+ merchant.get_id(),
+ &pi_fetch_constraints,
+ merchant.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
- let total_count = db
- .get_total_count_of_filtered_payment_attempts(
- merchant.get_id(),
- &active_attempt_ids,
- constraints.connector,
- constraints.payment_method,
- constraints.payment_method_type,
- constraints.authentication_type,
- constraints.merchant_connector_id,
- pi_fetch_constraints.get_profile_id_list(),
- merchant.storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let total_count = if constraints.has_no_attempt_filters() {
+ i64::try_from(active_attempt_ids.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while converting from usize to i64")
+ } else {
+ db.get_total_count_of_filtered_payment_attempts(
+ merchant.get_id(),
+ &active_attempt_ids,
+ constraints.connector,
+ constraints.payment_method,
+ constraints.payment_method_type,
+ constraints.authentication_type,
+ constraints.merchant_connector_id,
+ merchant.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ }?;
- Ok(services::ApplicationResponse::Json(
- api::PaymentListResponseV2 {
- count: data.len(),
- total_count,
- data,
+ Ok(services::ApplicationResponse::Json(
+ api::PaymentListResponseV2 {
+ count: data.len(),
+ total_count,
+ data,
+ },
+ ))
},
- ))
+ &metrics::PAYMENT_LIST_LATENCY,
+ &metrics::CONTEXT,
+ &[router_env::opentelemetry::KeyValue::new(
+ "merchant_id",
+ merchant.get_id().clone(),
+ )],
+ )
+ .await
}
#[cfg(all(feature = "olap", feature = "v1"))]
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 9f237c226b6..e8fbd7cb483 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1601,7 +1601,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>>,
- profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
self.diesel_store
@@ -1613,7 +1612,6 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
- profile_id_list,
storage_scheme,
)
.await
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index f3f1cd7cda0..1b55c838c45 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -21,6 +21,8 @@ counter_metric!(PAYMENT_OPS_COUNT, GLOBAL_METER);
counter_metric!(PAYMENT_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_PAYMENT, GLOBAL_METER);
+//TODO: This can be removed, added for payment list debugging
+histogram_metric!(PAYMENT_LIST_LATENCY, GLOBAL_METER);
counter_metric!(REFUND_COUNT, GLOBAL_METER);
counter_metric!(SUCCESSFUL_REFUND, GLOBAL_METER);
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 7410c5ee363..77ba1da0fcd 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -1035,7 +1035,7 @@ pub async fn profile_payments_list_by_filter(
|state, auth: auth::AuthenticationData, req, _| {
payments::apply_filters_on_payments(
state,
- auth.merchant_account,
+ auth.merchant_account.clone(),
auth.profile_id.map(|profile_id| vec![profile_id]),
auth.key_store,
req,
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 13c75e005c4..59fb1155480 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>>,
- _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 9053b7561ad..20b46a8460d 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -402,7 +402,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>>,
- profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = self
@@ -425,7 +424,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
- profile_id_list,
merchant_connector_id,
)
.await
@@ -1280,7 +1278,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>>,
- profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
@@ -1292,7 +1289,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
- profile_id_list,
storage_scheme,
)
.await
|
2024-10-15T21:20:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Skip count query if no filters are applied for attempts, in this we don't need to filter attempts as count of active attempt ids will be the total count.
- Profile id filter is already getting applied in intents, so removing it from last active attempts.
- Add logging around count 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
Closes [#6330](https://github.com/juspay/hyperswitch/issues/6330)
## How did you test it?
For Tests Lists working is same, same request and response:
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'x-api-key: dev_VWtyXkyK1Ath1vBNRMM4dqm18J0PVW8SiML4IsKtuzpsR5ojI0FCDBIY0ZRggpFf' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
Response will be something like
```
{
"count": 0,
"total_count": 0,
"data": []
}
```
Log is getting printed sucessfully
`Completed count query in 292.71075m
`
Results.
After hitting some 100 concurrent request for a very large dataset, we can clearly see without count query api is taking less time, and there is significant diff.
WIth count query
<img width="464" alt="Screenshot 2024-10-16 at 3 59 08 AM" src="https://github.com/user-attachments/assets/7e689588-672d-4148-978d-262ef71e6f94">
Without count query
<img width="433" alt="Screenshot 2024-10-16 at 3 59 21 AM" src="https://github.com/user-attachments/assets/fb261141-b857-4a81-b4c0-3abe6fdd6a58">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7e90031c68c7b93db996ee03e11c56b56a87402b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6271
|
Bug: [BUG] Do not use backticks in shell files
### Bug Description
These scripts:
- [`INSTALL_dependencies.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/INSTALL_dependencies.sh),
- [`hyperswitch_aws_setup.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/aws/hyperswitch_aws_setup.sh),
- [`hyperswitch_cleanup_setup.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/aws/hyperswitch_cleanup_setup.sh),
- [`add_connector.sh`](https://github.com/juspay/hyperswitch/tree/535f2f12f825be384a17fba8628d8517027bb6c6/scripts/add_connector.sh),
use the _deprecated_ backticks notation (cf. [SC2006](https://www.shellcheck.net/wiki/SC2006)).
### Expected Behavior
These scripts should follow the recommended guidelines.
### Actual Behavior
Use legacy notation, which might cause some maintenance issues.
### Steps To Reproduce
Not relevant.
### Context For The Bug
_No response_
### 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/INSTALL_dependencies.sh b/INSTALL_dependencies.sh
index 3ec36ccc66e..e1d666b97a3 100755
--- a/INSTALL_dependencies.sh
+++ b/INSTALL_dependencies.sh
@@ -37,7 +37,7 @@ set -o nounset
# utilities
# convert semver to comparable integer
-if [[ `id -u` -ne 0 ]]; then
+if [[ "$(id -u)" -ne 0 ]]; then
print_info "requires sudo"
SUDO=sudo
else
@@ -45,10 +45,10 @@ else
fi
ver () {
- printf "%03d%03d%03d%03d" `echo "$1" | tr '.' ' '`;
+ printf "%03d%03d%03d%03d" "$(echo "$1" | tr '.' ' ')";
}
-PROGNAME=`basename $0`
+PROGNAME="$(basename $0)"
print_info () {
echo -e "$PROGNAME: $*"
}
@@ -125,10 +125,10 @@ if command -v cargo > /dev/null; then
need_cmd rustc
- RUST_VERSION=`rustc -V | cut -d " " -f 2`
+ RUST_VERSION="$(rustc -V | cut -d " " -f 2)"
- _HAVE_VERSION=`ver ${RUST_VERSION}`
- _NEED_VERSION=`ver ${RUST_MSRV}`
+ _HAVE_VERSION="$(ver ${RUST_VERSION})"
+ _NEED_VERSION="$(ver ${RUST_MSRV})"
print_info "Found rust version \"${RUST_VERSION}\". MSRV is \"${RUST_MSRV}\""
@@ -166,7 +166,7 @@ install_dep () {
$INSTALL_CMD $*
}
-if [[ ! -x "`command -v psql`" ]] || [[ ! -x "`command -v redis-server`" ]] ; then
+if [[ ! -x "$(command -v psql)" ]] || [[ ! -x "$(command -v redis-server)" ]] ; then
print_info "Missing dependencies. Trying to install"
# java has an apt which seems to mess up when we look for apt
diff --git a/aws/hyperswitch_aws_setup.sh b/aws/hyperswitch_aws_setup.sh
index dd71b698e93..e3af286a58d 100644
--- a/aws/hyperswitch_aws_setup.sh
+++ b/aws/hyperswitch_aws_setup.sh
@@ -38,12 +38,11 @@ echo "Creating Security Group for Application..."
export EC2_SG="application-sg"
-echo `(aws ec2 create-security-group \
+echo "$(aws ec2 create-security-group \
--region $REGION \
--group-name $EC2_SG \
--description "Security Group for Hyperswitch EC2 instance" \
---tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \
-)`
+--tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]")"
export APP_SG_ID=$(aws ec2 describe-security-groups --group-names $EC2_SG --region $REGION --output text --query 'SecurityGroups[0].GroupId')
@@ -51,24 +50,23 @@ echo "Security Group for Application CREATED.\n"
echo "Creating Security Group ingress for port 80..."
-echo `aws ec2 authorize-security-group-ingress \
+echo "$(aws ec2 authorize-security-group-ingress \
--group-id $APP_SG_ID \
--protocol tcp \
--port 80 \
--cidr 0.0.0.0/0 \
---region $REGION`
+--region $REGION)"
echo "Security Group ingress for port 80 CREATED.\n"
-
echo "Creating Security Group ingress for port 22..."
-echo `aws ec2 authorize-security-group-ingress \
+echo "$(aws ec2 authorize-security-group-ingress \
--group-id $APP_SG_ID \
--protocol tcp \
--port 22 \
--cidr 0.0.0.0/0 \
---region $REGION`
+--region $REGION)"
echo "Security Group ingress for port 22 CREATED.\n"
@@ -78,11 +76,11 @@ echo "Security Group ingress for port 22 CREATED.\n"
echo "Creating Security Group for Elasticache..."
export REDIS_GROUP_NAME=redis-sg
-echo `aws ec2 create-security-group \
+echo "$(aws ec2 create-security-group \
--group-name $REDIS_GROUP_NAME \
--description "SG attached to elasticache" \
--tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \
---region $REGION`
+--region $REGION)"
echo "Security Group for Elasticache CREATED.\n"
@@ -91,12 +89,12 @@ echo "Creating Inbound rules for Redis..."
export REDIS_SG_ID=$(aws ec2 describe-security-groups --group-names $REDIS_GROUP_NAME --region $REGION --output text --query 'SecurityGroups[0].GroupId')
# CREATE INBOUND RULES
-echo `aws ec2 authorize-security-group-ingress \
+echo "$(aws ec2 authorize-security-group-ingress \
--group-id $REDIS_SG_ID \
--protocol tcp \
--port 6379 \
--source-group $EC2_SG \
---region $REGION`
+--region $REGION)"
echo "Inbound rules for Redis CREATED.\n"
@@ -105,11 +103,11 @@ echo "Inbound rules for Redis CREATED.\n"
echo "Creating Security Group for RDS..."
export RDS_GROUP_NAME=rds-sg
-echo `aws ec2 create-security-group \
+echo "$(aws ec2 create-security-group \
--group-name $RDS_GROUP_NAME \
--description "SG attached to RDS" \
--tag-specifications "ResourceType=security-group,Tags=[{Key=ManagedBy,Value=hyperswitch}]" \
---region $REGION`
+--region $REGION)"
echo "Security Group for RDS CREATED.\n"
@@ -118,21 +116,21 @@ echo "Creating Inbound rules for RDS..."
export RDS_SG_ID=$(aws ec2 describe-security-groups --group-names $RDS_GROUP_NAME --region $REGION --output text --query 'SecurityGroups[0].GroupId')
# CREATE INBOUND RULES
-echo `aws ec2 authorize-security-group-ingress \
+echo "$(aws ec2 authorize-security-group-ingress \
--group-id $RDS_SG_ID \
--protocol tcp \
--port 5432 \
--source-group $EC2_SG \
---region $REGION`
+--region $REGION)"
echo "Inbound rules for RDS CREATED.\n"
-echo `aws ec2 authorize-security-group-ingress \
+echo "$(aws ec2 authorize-security-group-ingress \
--group-id $RDS_SG_ID \
--protocol tcp \
--port 5432 \
--cidr 0.0.0.0/0 \
- --region $REGION`
+ --region $REGION)"
echo "Inbound rules for RDS (from any IP) CREATED.\n"
@@ -140,7 +138,7 @@ echo "Creating Elasticache with Redis engine..."
export CACHE_CLUSTER_ID=hyperswitch-cluster
-echo `aws elasticache create-cache-cluster \
+echo "$(aws elasticache create-cache-cluster \
--cache-cluster-id $CACHE_CLUSTER_ID \
--cache-node-type cache.t3.medium \
--engine redis \
@@ -148,14 +146,14 @@ echo `aws elasticache create-cache-cluster \
--security-group-ids $REDIS_SG_ID \
--engine-version 7.0 \
--tags "Key=ManagedBy,Value=hyperswitch" \
---region $REGION`
+--region $REGION)"
echo "Elasticache with Redis engine CREATED.\n"
echo "Creating RDS with PSQL..."
export DB_INSTANCE_ID=hyperswitch-db
-echo `aws rds create-db-instance \
+echo "$(aws rds create-db-instance \
--db-instance-identifier $DB_INSTANCE_ID\
--db-instance-class db.t3.micro \
--engine postgres \
@@ -166,7 +164,7 @@ echo `aws rds create-db-instance \
--region $REGION \
--db-name hyperswitch_db \
--tags "Key=ManagedBy,Value=hyperswitch" \
- --vpc-security-group-ids $RDS_SG_ID`
+ --vpc-security-group-ids $RDS_SG_ID)"
echo "RDS with PSQL CREATED.\n"
@@ -308,17 +306,17 @@ echo "EC2 instance launched.\n"
echo "Add Tags to EC2 instance..."
-echo `aws ec2 create-tags \
+echo "$(aws ec2 create-tags \
--resources $HYPERSWITCH_INSTANCE_ID \
--tags "Key=Name,Value=hyperswitch-router" \
---region $REGION`
+--region $REGION)"
echo "Tag added to EC2 instance.\n"
-echo `aws ec2 create-tags \
+echo "$(aws ec2 create-tags \
--resources $HYPERSWITCH_INSTANCE_ID \
--tags "Key=ManagedBy,Value=hyperswitch" \
---region $REGION`
+--region $REGION)"
echo "ManagedBy tag added to EC2 instance.\n"
diff --git a/aws/hyperswitch_cleanup_setup.sh b/aws/hyperswitch_cleanup_setup.sh
index 383f23d5bd0..df75623746c 100644
--- a/aws/hyperswitch_cleanup_setup.sh
+++ b/aws/hyperswitch_cleanup_setup.sh
@@ -45,7 +45,7 @@ for cluster_arn in $ALL_ELASTIC_CACHE; do
if [[ $? -eq 0 ]]; then
echo -n "Delete $cluster_id (Y/n)? "
if yes_or_no; then
- echo `aws elasticache delete-cache-cluster --region $REGION --cache-cluster-id $cluster_id`
+ echo "$(aws elasticache delete-cache-cluster --region $REGION --cache-cluster-id $cluster_id)"
fi
fi
done
@@ -59,7 +59,7 @@ echo -n "Deleting ( $ALL_KEY_PAIRS ) key pairs? (Y/n)?"
if yes_or_no; then
for KEY_ID in $ALL_KEY_PAIRS; do
- echo `aws ec2 delete-key-pair --key-pair-id $KEY_ID --region $REGION`
+ echo "$(aws ec2 delete-key-pair --key-pair-id $KEY_ID --region $REGION)"
done
fi
@@ -78,7 +78,7 @@ echo -n "Terminating ( $ALL_INSTANCES ) instances? (Y/n)?"
if yes_or_no; then
for INSTANCE_ID in $ALL_INSTANCES; do
- echo `aws ec2 terminate-instances --instance-ids $INSTANCE_ID --region $REGION`
+ echo "$(aws ec2 terminate-instances --instance-ids $INSTANCE_ID --region $REGION)"
done
fi
@@ -105,15 +105,15 @@ for resource_id in $ALL_DB_RESOURCES; do
echo -n "Create a snapshot before deleting ( $DB_INSTANCE_ID ) the database (Y/n)? "
if yes_or_no; then
- echo `aws rds delete-db-instance \
+ echo "$(aws rds delete-db-instance \
--db-instance-identifier $DB_INSTANCE_ID \
--region $REGION \
- --final-db-snapshot-identifier hyperswitch-db-snapshot-`date +%s``
+ --final-db-snapshot-identifier hyperswitch-db-snapshot-$(date +%s))"
else
- echo `aws rds delete-db-instance \
+ echo "$(aws rds delete-db-instance \
--region $REGION \
--db-instance-identifier $DB_INSTANCE_ID \
- --skip-final-snapshot`
+ --skip-final-snapshot)"
fi
fi
fi
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 2e12d829050..f90a8cbd3f5 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -8,7 +8,7 @@ function find_prev_connector() {
# Add new connector to existing list and sort it
connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
- res=`echo ${sorted[@]}`
+ res="$(echo ${sorted[@]})"
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
for i in "${!sorted[@]}"; do
if [ "${sorted[$i]}" = "$1" ] && [ $i != "0" ]; then
|
2024-10-16T08:15:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Use $(...) notation instead of legacy `...` in the shell files.
Removes the use of deprecated backticks notation (cf. [SC2006](https://www.shellcheck.net/wiki/SC2006)).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with 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/6271
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
899ec23565f99daaad821c1ec1482b4c0cc408c5
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6287
|
Bug: Add cypress test case for `network_transaction_id_and_card_details` recurring details MIT
Test cases should be added to `network_transaction_id_and_card_details` based recurring MIT flow
|
2024-11-14T06:06:56Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
[Reference pr](https://github.com/juspay/hyperswitch/pull/6245)
Add test cases MIT flow using the recurring_details of type `network_transaction_id_and_card_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).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Cypress tests
<img width="442" alt="image" src="https://github.com/user-attachments/assets/c871d675-1d44-49f9-9dd9-94cc3b58b9c0">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f24578310f44adf75c993ba42225554377399961
|
||
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
edd099886da9c46800a646fe809796a08eb78c99
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f3a869ea9a430f3b5177852fb74d0910dc8fbe17
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b79f75a7ab9ed63a75defa2b3c5f9c170fca493e
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e911ea4615294d136210bcf9a8bd4b3ab39ca85f
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## 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.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b7139483bb4735b7dfaf7e659ab33a16a90af1db
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- 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"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a3c2694943a985d27b5bc8b0371884d17a6ca34d
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- 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"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
55a97cc952aedd67451ed3785792e00d74f357ff
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6226
|
Bug: [FEAT] add support for Hashicorp Vault Engine
**Description:**
Cripta is a service which creates keys and maintains it (includes key rotation etc.) individually for different Merchants and Users.
Currently it uses the AWS KMS as the Master Key (Key Encryption Key) for encrypting and decrypting Data Encryption Keys, But this is limited to AWS, To support deployment of Keymanager in multiple clouds, We need to support more Engines.
**Getting started:**
Go through the [README](https://github.com/juspay/hyperswitch-encryption-service/blob/main/README.md) for guidelines on the structure and functionality.
**Possible implementation:**
1. Go through the Hashcorp Vault Engine Implementation [here](https://github.com/juspay/hyperswitch/tree/main/crates/external_services/src/hashicorp_vault).
2. Add the Implementation [here](https://github.com/juspay/hyperswitch-encryption-service/tree/main/src/crypto)
3. Create a feature for Hashicorp Vault.
4. Add Initializer for Hashicorp Vault [here](https://github.com/juspay/hyperswitch-encryption-service/blob/main/src/config.rs#L174).
**Reference:**
- [Hyperswitch Keymanager](https://docs.hyperswitch.io/security-and-compliance/security#key-manager-service-encryption)
- Language: Rust
- Difficulty: Medium
### 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).
- For this issue, please raise a PR on the https://github.com/juspay/hyperswitch-encryption-service repo, and link the issue.
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/Cargo.toml b/crates/router/Cargo.toml
index 5211b034eb5..982c1130207 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -7,6 +7,7 @@ default-run = "router"
rust-version = "1.63"
readme = "README.md"
license = "Apache-2.0"
+build = "src/build.rs"
[features]
default = []
@@ -73,6 +74,9 @@ time = { version = "0.3.14", features = ["macros"] }
tokio = "1.21.2"
toml = "0.5.9"
+[build-dependencies]
+router_env = { version = "0.1.0", path = "../router_env", default-features = false, features = ["vergen"] }
+
[[bin]]
name = "router"
path = "src/bin/router.rs"
diff --git a/crates/router/src/build.rs b/crates/router/src/build.rs
new file mode 100644
index 00000000000..4b07385af68
--- /dev/null
+++ b/crates/router/src/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ router_env::vergen::generate_cargo_instructions();
+}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index d4dfbfb360c..6d1dd47e98d 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -11,6 +11,7 @@ use crate::{
};
#[derive(StructOpt, Default)]
+#[structopt(version = router_env::version!())]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 53f994356ff..e97dc09d198 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -27,12 +27,13 @@ tracing-appender = "0.2.2"
tracing-core = "0.1.29"
tracing-opentelemetry = { version = "0.17" }
tracing-subscriber = { version = "0.3.15", default-features = true, features = ["json", "env-filter", "registry"] }
+vergen = { version = "7.4.2", optional = true }
[dev-dependencies]
tokio = { version = "1.21.2", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
-vergen = { version = "7.4.2" }
+vergen = "7.4.2"
[features]
default = ["actix_web"]
diff --git a/crates/router_env/src/build.rs b/crates/router_env/src/build.rs
index 28436458f30..aca12d76a1d 100644
--- a/crates/router_env/src/build.rs
+++ b/crates/router_env/src/build.rs
@@ -1,50 +1,5 @@
-use vergen::{vergen, Config, ShaKind};
+include!("vergen.rs");
fn main() {
- let mut config = Config::default();
-
- let build = config.build_mut();
- *build.enabled_mut() = false;
- *build.skip_if_error_mut() = true;
-
- let cargo = config.cargo_mut();
- *cargo.enabled_mut() = true;
- *cargo.features_mut() = false;
- *cargo.profile_mut() = true;
- *cargo.target_triple_mut() = true;
-
- let git = config.git_mut();
- *git.enabled_mut() = true;
- *git.commit_author_mut() = false;
- *git.commit_count_mut() = false;
- *git.commit_message_mut() = false;
- *git.commit_timestamp_mut() = true;
- *git.semver_mut() = false;
- *git.skip_if_error_mut() = true;
- *git.sha_kind_mut() = ShaKind::Both;
- *git.skip_if_error_mut() = true;
-
- let rustc = config.rustc_mut();
- *rustc.enabled_mut() = true;
- *rustc.channel_mut() = false;
- *rustc.commit_date_mut() = false;
- *rustc.host_triple_mut() = false;
- *rustc.llvm_version_mut() = false;
- *rustc.semver_mut() = true;
- *rustc.sha_mut() = true; // required for sever been available
- *rustc.skip_if_error_mut() = true;
-
- let sysinfo = config.sysinfo_mut();
- *sysinfo.enabled_mut() = false;
- *sysinfo.os_version_mut() = false;
- *sysinfo.user_mut() = false;
- *sysinfo.memory_mut() = false;
- *sysinfo.cpu_vendor_mut() = false;
- *sysinfo.cpu_core_count_mut() = false;
- *sysinfo.cpu_name_mut() = false;
- *sysinfo.cpu_brand_mut() = false;
- *sysinfo.cpu_frequency_mut() = false;
- *sysinfo.skip_if_error_mut() = true;
-
- vergen(config).expect("Problem determining current platform characteristics");
+ generate_cargo_instructions();
}
diff --git a/crates/router_env/src/env.rs b/crates/router_env/src/env.rs
index 229186f6dc5..518a1cac0cf 100644
--- a/crates/router_env/src/env.rs
+++ b/crates/router_env/src/env.rs
@@ -73,23 +73,25 @@ pub fn workspace_path() -> PathBuf {
}
}
-/// Version defined in the crate file.
+/// Version of the crate containing the following information:
///
-/// Example: `0.1.0`.
+/// - Semantic Version from the latest git tag. If tags are not present in the repository, crate
+/// version from the crate manifest is used instead.
+/// - Short hash of the latest git commit.
+/// - Timestamp of the latest git commit.
///
-
+/// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`.
#[macro_export]
macro_rules! version {
- (
- ) => {{
+ () => {
concat!(
- env!("CARGO_PKG_VERSION"),
+ env!("VERGEN_GIT_SEMVER"),
"-",
env!("VERGEN_GIT_SHA_SHORT"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
- }};
+ };
}
///
@@ -107,8 +109,7 @@ macro_rules! version {
#[macro_export]
macro_rules! build {
- (
- ) => {{
+ () => {
concat!(
env!("CARGO_PKG_VERSION"),
"-",
@@ -122,7 +123,7 @@ macro_rules! build {
"-",
env!("VERGEN_CARGO_TARGET_TRIPLE"),
)
- }};
+ };
}
///
@@ -133,10 +134,9 @@ macro_rules! build {
#[macro_export]
macro_rules! commit {
- (
- ) => {{
+ () => {
env!("VERGEN_GIT_SHA")
- }};
+ };
}
// ///
@@ -166,10 +166,9 @@ macro_rules! commit {
#[macro_export]
macro_rules! service_name {
- (
- ) => {{
+ () => {
env!("CARGO_CRATE_NAME")
- }};
+ };
}
///
@@ -180,8 +179,7 @@ macro_rules! service_name {
#[macro_export]
macro_rules! profile {
- (
- ) => {
+ () => {
env!("VERGEN_CARGO_PROFILE")
};
}
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index 3ecefb7a362..93eab6e2dcf 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -19,10 +19,12 @@
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
pub mod env;
-#[doc(inline)]
-pub use env::*;
-
pub mod logger;
+/// `cargo` build instructions generation for obtaining information about the application
+/// environment.
+#[cfg(feature = "vergen")]
+pub mod vergen;
+
// pub use literally;
#[doc(inline)]
pub use logger::*;
@@ -31,3 +33,6 @@ pub use tracing;
#[cfg(feature = "actix_web")]
pub use tracing_actix_web;
pub use tracing_appender;
+
+#[doc(inline)]
+pub use self::env::*;
diff --git a/crates/router_env/src/vergen.rs b/crates/router_env/src/vergen.rs
new file mode 100644
index 00000000000..22e16605a2b
--- /dev/null
+++ b/crates/router_env/src/vergen.rs
@@ -0,0 +1,60 @@
+/// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions.
+///
+/// This function should be typically called within build scripts to generate `cargo` build
+/// instructions for the corresponding crate.
+///
+/// # Panics
+///
+/// Panics if `vergen` fails to generate `cargo` build instructions.
+#[allow(clippy::expect_used)]
+pub fn generate_cargo_instructions() {
+ use vergen::{vergen, Config, ShaKind};
+
+ let mut config = Config::default();
+
+ let build = config.build_mut();
+ *build.enabled_mut() = false;
+ *build.skip_if_error_mut() = true;
+
+ let cargo = config.cargo_mut();
+ *cargo.enabled_mut() = true;
+ *cargo.features_mut() = false;
+ *cargo.profile_mut() = true;
+ *cargo.target_triple_mut() = true;
+
+ let git = config.git_mut();
+ *git.enabled_mut() = true;
+ *git.commit_author_mut() = false;
+ *git.commit_count_mut() = false;
+ *git.commit_message_mut() = false;
+ *git.commit_timestamp_mut() = true;
+ *git.semver_mut() = true;
+ *git.semver_dirty_mut() = Some("-dirty");
+ *git.skip_if_error_mut() = true;
+ *git.sha_kind_mut() = ShaKind::Both;
+ *git.skip_if_error_mut() = true;
+
+ let rustc = config.rustc_mut();
+ *rustc.enabled_mut() = true;
+ *rustc.channel_mut() = false;
+ *rustc.commit_date_mut() = false;
+ *rustc.host_triple_mut() = false;
+ *rustc.llvm_version_mut() = false;
+ *rustc.semver_mut() = true;
+ *rustc.sha_mut() = true; // required for semver to be available
+ *rustc.skip_if_error_mut() = true;
+
+ let sysinfo = config.sysinfo_mut();
+ *sysinfo.enabled_mut() = false;
+ *sysinfo.os_version_mut() = false;
+ *sysinfo.user_mut() = false;
+ *sysinfo.memory_mut() = false;
+ *sysinfo.cpu_vendor_mut() = false;
+ *sysinfo.cpu_core_count_mut() = false;
+ *sysinfo.cpu_name_mut() = false;
+ *sysinfo.cpu_brand_mut() = false;
+ *sysinfo.cpu_frequency_mut() = false;
+ *sysinfo.skip_if_error_mut() = true;
+
+ vergen(config).expect("Failed to generate `cargo` build instructions");
+}
|
2022-11-25T21:13:22Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
## Description
<!-- Describe your changes in detail -->
This PR adds the following two fields of information to the output of `router --version`:
- Short git commit hash
- Git commit timestamp
In addition, the version number in the output is obtained in the below fashion:
- If git tags are present in the repository which follow Semantic Versioning, the Semantic Version from the latest git tag is used.
- If git tags are not present in the repository, the crate version from the crate manifest is used instead.
- If git tags are present and the working directory is dirty (files are modified), then the Semantic Version also includes a `-dirty` suffix.
### Additional Changes
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
N/A
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless its an obvious bug or documentation fix
that will have little conversation).
-->
I felt the need to include the git commit hash when adding the bug report template in #20. I realized that having the git commit hash included in the output of `router --version` would ease analyzing bug reports for us maintainers. Thus, the PR.
## How did you test 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 testing.
- When no Semantic Versioned git tags are present: `router 0.2.0-d411595-2022-11-25T11:33:52Z`
- When Semantic Versioned git tags are present: `router v0.1.0-d411595-2022-11-25T11:33:52Z`
- When Semantic Versioned git tags are present and the working directory is dirty: `router v0.1.0-dirty-d411595-2022-11-25T11:33:52Z`
PS: Let me know if the above outputs look hard to read, we can have them separated by spaces instead, to have the output like so: `router v0.1.0 d411595 2022-11-25T11:33:52Z`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
3e0298032b5c9535d418f50ab440a4aeaf265aba
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
962afbd084458e9afb11a0278a8210edd9226a3d
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
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
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a3c2694943a985d27b5bc8b0371884d17a6ca34d
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently 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"
}
]'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4dae29221f2d24a0f4299e641cfe22ab705fae25
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- 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.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
edd099886da9c46800a646fe809796a08eb78c99
|
|
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
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## 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)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
387f02ee273e1bbf50e7b3882f5e9468d59f2c5b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-6177
|
Bug: [FEATURE] integrate 3DS for Worldpay connector
### Feature Description
WorldPay offers 3DS capabilities for a card txn. Same needs to be integrated in HyperSwitch.
Flow - https://developer.worldpay.com/products/access/3ds/web
### Possible Implementation
Implementing 3DS for WorldPay requires one additional step of running DDC flows. Flow can be looked at in WorldPay's dev docs
1. Redirect to Worldpay's DDC
2. Redirect to Wordlpay's 3DS redirection form
3. Capture details in HyperSwitch's `/redirect/complete` flow
4. Perform a PSync (optional)
Reference
https://developer.worldpay.com/products/access/3ds/web
### 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/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 85c69824892..0627fa0048a 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -171,11 +171,23 @@ impl PaymentAttempt {
merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
) -> StorageResult<Self> {
+ let (txn_id, txn_data) = common_utils::types::ConnectorTransactionId::form_id_and_data(
+ connector_txn_id.to_string(),
+ );
+ let connector_transaction_id = txn_id
+ .get_txn_id(txn_data.as_ref())
+ .change_context(DatabaseError::Others)
+ .attach_printable_lazy(|| {
+ format!(
+ "Failed to retrieve txn_id for ({:?}, {:?})",
+ txn_id, txn_data
+ )
+ })?;
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
- .and(dsl::connector_transaction_id.eq(connector_txn_id.to_owned())),
+ .and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())),
)
.await
}
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index eca56b8c866..6682ac1ad44 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -163,6 +163,12 @@ pub enum RedirectForm {
Mifinity {
initialization_token: String,
},
+ WorldpayDDCForm {
+ endpoint: url::Url,
+ method: Method,
+ form_fields: HashMap<String, String>,
+ collection_id: Option<String>,
+ },
}
impl From<(url::Url, Method)> for RedirectForm {
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index 7a4c4c5da97..97da36f39b3 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -624,6 +624,113 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
+impl api::PaymentsCompleteAuthorize for Worldpay {}
+impl
+ ConnectorIntegration<
+ api::CompleteAuthorize,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ > for Worldpay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
+ let stage = match req.status {
+ enums::AttemptStatus::DeviceDataCollectionPending => "3dsDeviceData".to_string(),
+ _ => "3dsChallenges".to_string(),
+ };
+ Ok(format!(
+ "{}api/payments/{connector_payment_id}/{stage}",
+ self.base_url(connectors),
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let req_obj = WorldpayCompleteAuthorizationRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(req_obj)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ let response: WorldpayPaymentsResponse = res
+ .response
+ .parse_struct("WorldpayPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ let optional_correlation_id = res.headers.and_then(|headers| {
+ headers
+ .get("WP-CorrelationId")
+ .and_then(|header_value| header_value.to_str().ok())
+ .map(|id| id.to_string())
+ });
+ types::RouterData::foreign_try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ optional_correlation_id,
+ ))
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl api::Refund for Worldpay {}
impl api::RefundExecute for Worldpay {}
impl api::RefundSync for Worldpay {}
@@ -900,3 +1007,20 @@ impl api::IncomingWebhook for Worldpay {
Ok(Box::new(psync_body))
}
}
+
+impl services::ConnectorRedirectResponse for Worldpay {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ action: services::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
+ match action {
+ services::PaymentAction::CompleteAuthorize => Ok(enums::CallConnectorAction::Trigger),
+ services::PaymentAction::PSync
+ | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Avoid)
+ }
+ }
+ }
+}
diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs
index 3d0be891ebb..b0fa85a64c3 100644
--- a/crates/router/src/connector/worldpay/requests.rs
+++ b/crates/router/src/connector/worldpay/requests.rs
@@ -31,6 +31,8 @@ pub struct Instruction {
pub value: PaymentValue,
#[serde(skip_serializing_if = "Option::is_none")]
pub debt_repayment: Option<bool>,
+ #[serde(rename = "threeDS")]
+ pub three_ds: Option<ThreeDSRequest>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -187,6 +189,44 @@ pub struct AutoSettlement {
pub auto: bool,
}
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ThreeDSRequest {
+ #[serde(rename = "type")]
+ pub three_ds_type: String,
+ pub mode: String,
+ pub device_data: ThreeDSRequestDeviceData,
+ pub challenge: ThreeDSRequestChallenge,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ThreeDSRequestDeviceData {
+ pub accept_header: String,
+ pub user_agent_header: String,
+ pub browser_language: Option<String>,
+ pub browser_screen_width: Option<u32>,
+ pub browser_screen_height: Option<u32>,
+ pub browser_color_depth: Option<String>,
+ pub time_zone: Option<String>,
+ pub browser_java_enabled: Option<bool>,
+ pub browser_javascript_enabled: Option<bool>,
+ pub channel: Option<ThreeDSRequestChannel>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ThreeDSRequestChannel {
+ Browser,
+ Native,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ThreeDSRequestChallenge {
+ pub return_url: String,
+}
+
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentMethod {
@@ -237,3 +277,10 @@ pub struct WorldpayPartialRequest {
pub value: PaymentValue,
pub reference: String,
}
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorldpayCompleteAuthorizationRequest {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub collection_reference: Option<String>,
+}
diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs
index 0a7f690c3aa..edc3c26948f 100644
--- a/crates/router/src/connector/worldpay/response.rs
+++ b/crates/router/src/connector/worldpay/response.rs
@@ -1,6 +1,7 @@
use error_stack::ResultExt;
use masking::Secret;
use serde::{Deserialize, Serialize};
+use url::Url;
use super::requests::*;
use crate::core::errors;
@@ -10,7 +11,7 @@ pub struct WorldpayPaymentsResponse {
pub outcome: PaymentOutcome,
pub transaction_reference: Option<String>,
#[serde(flatten)]
- pub other_fields: WorldpayPaymentResponseFields,
+ pub other_fields: Option<WorldpayPaymentResponseFields>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -20,13 +21,13 @@ pub enum WorldpayPaymentResponseFields {
DDCResponse(DDCResponse),
FraudHighRisk(FraudHighRiskResponse),
RefusedResponse(RefusedResponse),
+ ThreeDsChallenged(ThreeDsChallengedResponse),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedResponse {
- #[serde(skip_serializing_if = "Option::is_none")]
- pub payment_instrument: Option<PaymentsResPaymentInstrument>,
+ pub payment_instrument: PaymentsResPaymentInstrument,
#[serde(skip_serializing_if = "Option::is_none")]
pub issuer: Option<Issuer>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -67,6 +68,34 @@ pub struct ThreeDsResponse {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
+pub struct ThreeDsChallengedResponse {
+ pub authentication: AuthenticationResponse,
+ pub challenge: ThreeDsChallenge,
+ #[serde(rename = "_actions")]
+ pub actions: CompleteThreeDsActionLink,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct AuthenticationResponse {
+ pub version: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct ThreeDsChallenge {
+ pub reference: String,
+ pub url: Url,
+ pub jwt: Secret<String>,
+ pub payload: Secret<String>,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct CompleteThreeDsActionLink {
+ #[serde(rename = "complete3dsChallenge")]
+ pub complete_three_ds_challenge: ActionLink,
+}
+
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
pub enum IssuerResponse {
Challenged,
Frictionless,
@@ -82,16 +111,15 @@ pub struct DDCResponse {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DDCToken {
- pub jwt: String,
- pub url: String,
- pub bin: String,
+ pub jwt: Secret<String>,
+ pub url: Url,
+ pub bin: Secret<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DDCActionLink {
#[serde(rename = "supply3dsDeviceData")]
supply_ddc_data: ActionLink,
- method: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -105,11 +133,32 @@ pub enum PaymentOutcome {
FraudHighRisk,
#[serde(alias = "3dsDeviceDataRequired")]
ThreeDsDeviceDataRequired,
- ThreeDsChallenged,
SentForCancellation,
#[serde(alias = "3dsAuthenticationFailed")]
ThreeDsAuthenticationFailed,
SentForPartialRefund,
+ #[serde(alias = "3dsChallenged")]
+ ThreeDsChallenged,
+ #[serde(alias = "3dsUnavailable")]
+ ThreeDsUnavailable,
+}
+
+impl std::fmt::Display for PaymentOutcome {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Authorized => write!(f, "authorized"),
+ Self::Refused => write!(f, "refused"),
+ Self::SentForSettlement => write!(f, "sentForSettlement"),
+ Self::SentForRefund => write!(f, "sentForRefund"),
+ Self::FraudHighRisk => write!(f, "fraudHighRisk"),
+ Self::ThreeDsDeviceDataRequired => write!(f, "3dsDeviceDataRequired"),
+ Self::SentForCancellation => write!(f, "sentForCancellation"),
+ Self::ThreeDsAuthenticationFailed => write!(f, "3dsAuthenticationFailed"),
+ Self::SentForPartialRefund => write!(f, "sentForPartialRefund"),
+ Self::ThreeDsChallenged => write!(f, "3dsChallenged"),
+ Self::ThreeDsUnavailable => write!(f, "3dsUnavailable"),
+ }
+ }
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -202,30 +251,33 @@ pub fn get_resource_id<T, F>(
where
F: Fn(String) -> T,
{
- let reference_id = match response.other_fields {
- WorldpayPaymentResponseFields::AuthorizedResponse(res) => res
- .links
- .as_ref()
- .and_then(|link| link.self_link.href.rsplit_once('/'))
- .map(|(_, h)| urlencoding::decode(h))
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)?
- .map(|s| transform_fn(s.into_owned())),
- WorldpayPaymentResponseFields::DDCResponse(res) => res
- .actions
- .supply_ddc_data
- .href
- .split('/')
- .rev()
- .nth(1)
- .map(urlencoding::decode)
- .transpose()
- .change_context(errors::ConnectorError::ResponseHandlingFailed)?
- .map(|s| transform_fn(s.into_owned())),
- WorldpayPaymentResponseFields::FraudHighRisk(_) => None,
- WorldpayPaymentResponseFields::RefusedResponse(_) => None,
- };
- reference_id
+ let optional_reference_id = response
+ .other_fields
+ .as_ref()
+ .and_then(|other_fields| match other_fields {
+ WorldpayPaymentResponseFields::AuthorizedResponse(res) => res
+ .links
+ .as_ref()
+ .and_then(|link| link.self_link.href.rsplit_once('/').map(|(_, h)| h)),
+ WorldpayPaymentResponseFields::DDCResponse(res) => {
+ res.actions.supply_ddc_data.href.split('/').nth_back(1)
+ }
+ WorldpayPaymentResponseFields::ThreeDsChallenged(res) => res
+ .actions
+ .complete_three_ds_challenge
+ .href
+ .split('/')
+ .nth_back(1),
+ WorldpayPaymentResponseFields::FraudHighRisk(_)
+ | WorldpayPaymentResponseFields::RefusedResponse(_) => None,
+ })
+ .map(|href| {
+ urlencoding::decode(href)
+ .map(|s| transform_fn(s.into_owned()))
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ })
+ .transpose()?;
+ optional_reference_id
.or_else(|| connector_transaction_id.map(transform_fn))
.ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
@@ -256,8 +308,8 @@ 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 payment_instrument_type: Option<String>,
+ #[serde(rename = "type")]
+ pub payment_instrument_type: String,
pub card_bin: Option<String>,
pub last_four: Option<String>,
pub expiry_date: Option<ExpiryDate>,
@@ -268,22 +320,6 @@ pub struct PaymentsResPaymentInstrument {
pub payment_account_reference: Option<String>,
}
-impl PaymentsResPaymentInstrument {
- pub fn new() -> Self {
- Self {
- payment_instrument_type: None,
- card_bin: None,
- last_four: None,
- category: None,
- expiry_date: None,
- card_brand: None,
- funding_type: None,
- issuer_name: None,
- payment_account_reference: None,
- }
- }
-}
-
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RiskFactorsInner {
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index a0f2bfd2508..a28d3bff7ed 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -1,17 +1,20 @@
+use std::collections::HashMap;
+
use api_models::payments::Address;
use base64::Engine;
use common_utils::{errors::CustomResult, ext_traits::OptionExt, pii, types::MinorUnit};
use diesel_models::enums;
use error_stack::ResultExt;
-use hyperswitch_connectors::utils::RouterData;
+use hyperswitch_connectors::utils::{PaymentsAuthorizeRequestData, RouterData};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use super::{requests::*, response::*};
use crate::{
- connector::utils,
+ connector::utils::{self, AddressData},
consts,
core::errors,
+ services,
types::{
self, domain, transformers::ForeignTryFrom, PaymentsAuthorizeData, PaymentsResponseData,
},
@@ -65,49 +68,40 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for WorldpayConnectorMetadataObject
fn fetch_payment_instrument(
payment_method: domain::PaymentMethodData,
billing_address: Option<&Address>,
- auth_type: enums::AuthenticationType,
) -> CustomResult<PaymentInstrument, errors::ConnectorError> {
match payment_method {
- domain::PaymentMethodData::Card(card) => {
- if auth_type == enums::AuthenticationType::ThreeDs {
- return Err(errors::ConnectorError::NotImplemented(
- "ThreeDS flow through worldpay".to_string(),
- )
- .into());
- }
- Ok(PaymentInstrument::Card(CardPayment {
- payment_type: PaymentType::Plain,
- 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,
- 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::Card(card) => Ok(PaymentInstrument::Card(CardPayment {
+ payment_type: PaymentType::Plain,
+ 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,
+ cvc: card.card_cvc,
+ card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()),
+ billing_address: if let Some(address) =
+ billing_address.and_then(|addr| addr.address.clone())
+ {
+ Some(BillingAddress {
+ address1: address.line1,
+ 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) => {
Ok(PaymentInstrument::Googlepay(WalletPayment {
@@ -230,6 +224,53 @@ impl
config: "metadata.merchant_name",
},
)?;
+ let three_ds = match item.router_data.auth_type {
+ enums::AuthenticationType::ThreeDs => {
+ let browser_info = item
+ .router_data
+ .request
+ .browser_info
+ .clone()
+ .get_required_value("browser_info")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "browser_info",
+ })?;
+ let accept_header = browser_info
+ .accept_header
+ .get_required_value("accept_header")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "accept_header",
+ })?;
+ let user_agent_header = browser_info
+ .user_agent
+ .get_required_value("user_agent")
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "user_agent",
+ })?;
+ Some(ThreeDSRequest {
+ three_ds_type: "integrated".to_string(),
+ mode: "always".to_string(),
+ device_data: ThreeDSRequestDeviceData {
+ accept_header,
+ user_agent_header,
+ browser_language: browser_info.language.clone(),
+ browser_screen_width: browser_info.screen_width,
+ browser_screen_height: browser_info.screen_height,
+ browser_color_depth: browser_info
+ .color_depth
+ .map(|depth| depth.to_string()),
+ time_zone: browser_info.time_zone.map(|tz| tz.to_string()),
+ browser_java_enabled: browser_info.java_enabled,
+ browser_javascript_enabled: browser_info.java_script_enabled,
+ channel: Some(ThreeDSRequestChannel::Browser),
+ },
+ challenge: ThreeDSRequestChallenge {
+ return_url: item.router_data.request.get_complete_authorize_url()?,
+ },
+ })
+ }
+ _ => None,
+ };
Ok(Self {
instruction: Instruction {
settlement: item
@@ -252,7 +293,6 @@ impl
payment_instrument: fetch_payment_instrument(
item.router_data.request.payment_method_data.clone(),
item.router_data.get_optional_billing(),
- item.router_data.auth_type,
)?,
narrative: InstructionNarrative {
line1: merchant_name.expose(),
@@ -262,6 +302,7 @@ impl
currency: item.router_data.request.currency,
},
debt_repayment: None,
+ three_ds,
},
merchant: Merchant {
entity: entity_id.clone(),
@@ -321,6 +362,7 @@ impl From<PaymentOutcome> for enums::AttemptStatus {
Self::AutoRefunded
}
PaymentOutcome::Refused | PaymentOutcome::FraudHighRisk => Self::Failure,
+ PaymentOutcome::ThreeDsUnavailable => Self::AuthenticationFailed,
}
}
}
@@ -363,42 +405,105 @@ impl From<EventType> for enums::RefundStatus {
}
}
-impl
+impl<F, T>
ForeignTryFrom<(
- types::PaymentsResponseRouterData<WorldpayPaymentsResponse>,
+ types::ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>,
Option<String>,
- )> for types::PaymentsAuthorizeRouterData
+ )> for types::RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: (
- types::PaymentsResponseRouterData<WorldpayPaymentsResponse>,
+ types::ResponseRouterData<F, WorldpayPaymentsResponse, T, PaymentsResponseData>,
Option<String>,
),
) -> Result<Self, Self::Error> {
let (router_data, optional_correlation_id) = item;
- let description = match router_data.response.other_fields {
- WorldpayPaymentResponseFields::AuthorizedResponse(ref res) => res.description.clone(),
- WorldpayPaymentResponseFields::DDCResponse(_)
- | WorldpayPaymentResponseFields::FraudHighRisk(_)
- | WorldpayPaymentResponseFields::RefusedResponse(_) => None,
+ let (description, redirection_data) = router_data
+ .response
+ .other_fields
+ .as_ref()
+ .map(|other_fields| match other_fields {
+ WorldpayPaymentResponseFields::AuthorizedResponse(res) => {
+ (res.description.clone(), None)
+ }
+ WorldpayPaymentResponseFields::DDCResponse(res) => (
+ None,
+ Some(services::RedirectForm::WorldpayDDCForm {
+ endpoint: res.device_data_collection.url.clone(),
+ method: common_utils::request::Method::Post,
+ collection_id: Some("SessionId".to_string()),
+ form_fields: HashMap::from([
+ (
+ "Bin".to_string(),
+ res.device_data_collection.bin.clone().expose(),
+ ),
+ (
+ "JWT".to_string(),
+ res.device_data_collection.jwt.clone().expose(),
+ ),
+ ]),
+ }),
+ ),
+ WorldpayPaymentResponseFields::ThreeDsChallenged(res) => (
+ None,
+ Some(services::RedirectForm::Form {
+ endpoint: res.challenge.url.to_string(),
+ method: common_utils::request::Method::Post,
+ form_fields: HashMap::from([(
+ "JWT".to_string(),
+ res.challenge.jwt.clone().expose(),
+ )]),
+ }),
+ ),
+ WorldpayPaymentResponseFields::FraudHighRisk(_)
+ | WorldpayPaymentResponseFields::RefusedResponse(_) => (None, None),
+ })
+ .unwrap_or((None, None));
+ let worldpay_status = router_data.response.outcome.clone();
+ let optional_reason = match worldpay_status {
+ PaymentOutcome::ThreeDsAuthenticationFailed => {
+ Some("3DS authentication failed from issuer".to_string())
+ }
+ PaymentOutcome::ThreeDsUnavailable => {
+ Some("3DS authentication unavailable from issuer".to_string())
+ }
+ PaymentOutcome::FraudHighRisk => {
+ Some("Transaction marked as high risk by Worldpay".to_string())
+ }
+ PaymentOutcome::Refused => Some("Transaction refused by issuer".to_string()),
+ _ => None,
};
- Ok(Self {
- status: enums::AttemptStatus::from(router_data.response.outcome.clone()),
- description,
- response: Ok(PaymentsResponseData::TransactionResponse {
+ let status = enums::AttemptStatus::from(worldpay_status.clone());
+ let response = optional_reason.map_or(
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::foreign_try_from((
router_data.response,
optional_correlation_id.clone(),
))?,
- redirection_data: None,
+ redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: optional_correlation_id,
+ connector_response_reference_id: optional_correlation_id.clone(),
incremental_authorization_allowed: None,
charge_id: None,
}),
+ |reason| {
+ Err(types::ErrorResponse {
+ code: worldpay_status.to_string(),
+ message: reason.clone(),
+ reason: Some(reason),
+ status_code: router_data.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: optional_correlation_id,
+ })
+ },
+ );
+ Ok(Self {
+ status,
+ description,
+ response,
..router_data.data
})
}
@@ -459,3 +564,17 @@ impl ForeignTryFrom<(WorldpayPaymentsResponse, Option<String>)> for types::Respo
get_resource_id(item.0, item.1, Self::ConnectorTransactionId)
}
}
+
+impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for WorldpayCompleteAuthorizationRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
+ let params = item
+ .request
+ .redirect_response
+ .as_ref()
+ .and_then(|redirect_response| redirect_response.params.as_ref())
+ .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
+ serde_urlencoded::from_str::<Self>(params.peek())
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ }
+}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index babf393bb3a..700fff16cf5 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -240,7 +240,6 @@ default_imp_for_complete_authorize!(
connector::Wise,
connector::Wellsfargo,
connector::Wellsfargopayout,
- connector::Worldpay,
connector::Zen,
connector::Zsl
);
@@ -472,7 +471,6 @@ default_imp_for_connector_redirect_response!(
connector::Wellsfargo,
connector::Wellsfargopayout,
connector::Wise,
- connector::Worldpay,
connector::Zsl
);
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 579a4ac4ffd..0d84ba9c30f 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1809,6 +1809,135 @@ pub fn build_redirection_form(
}
}
+ RedirectForm::WorldpayDDCForm {
+ endpoint,
+ method,
+ form_fields,
+ collection_id,
+ } => maud::html! {
+ (maud::DOCTYPE)
+ html {
+ meta name="viewport" content="width=device-width, initial-scale=1";
+ head {
+ (PreEscaped(r##"
+ <style>
+ #loader1 {
+ width: 500px;
+ }
+ @media max-width: 600px {
+ #loader1 {
+ width: 200px;
+ }
+ }
+ </style>
+ "##))
+ }
+
+ body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
+ div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
+ (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
+ (PreEscaped(r#"
+ <script>
+ var anime = bodymovin.loadAnimation({
+ container: document.getElementById('loader1'),
+ renderer: 'svg',
+ loop: true,
+ autoplay: true,
+ name: 'hyperswitch loader',
+ animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]}
+ })
+ </script>
+ "#))
+ h3 style="text-align: center;" { "Please wait while we process your payment..." }
+
+ script {
+ (PreEscaped(format!(
+ r#"
+ function submitCollectionReference(collectionReference) {{
+ var redirectPathname = window.location.pathname.replace(/payments\/redirect\/(\w+)\/(\w+)\/\w+/, "payments/$1/$2/redirect/complete/worldpay");
+ var redirectUrl = window.location.origin + redirectPathname;
+ try {{
+ if (typeof collectionReference === "string" && collectionReference.length > 0) {{
+ var form = document.createElement("form");
+ form.action = redirectPathname;
+ form.method = "GET";
+ var input = document.createElement("input");
+ input.type = "hidden";
+ input.name = "collectionReference";
+ input.value = collectionReference;
+ form.appendChild(input);
+ document.body.appendChild(form);
+ form.submit();;
+ }} else {{
+ window.location.replace(redirectUrl);
+ }}
+ }} catch (error) {{
+ window.location.replace(redirectUrl);
+ }}
+ }}
+ var allowedHost = "{}";
+ var collectionField = "{}";
+ window.addEventListener("message", function(event) {{
+ if (event.origin === allowedHost) {{
+ try {{
+ var data = JSON.parse(event.data);
+ if (collectionField.length > 0) {{
+ var collectionReference = data[collectionField];
+ return submitCollectionReference(collectionReference);
+ }} else {{
+ console.error("Collection field not found in event data (" + collectionField + ")");
+ }}
+ }} catch (error) {{
+ console.error("Error parsing event data: ", error);
+ }}
+ }} else {{
+ console.error("Invalid origin: " + event.origin, "Expected origin: " + allowedHost);
+ }}
+
+ submitCollectionReference("");
+ }});
+
+ // Redirect within 8 seconds if no collection reference is received
+ window.setTimeout(submitCollectionReference, 8000);
+ "#,
+ endpoint.host_str().map_or(endpoint.as_ref().split('/').take(3).collect::<Vec<&str>>().join("/"), |host| format!("{}://{}", endpoint.scheme(), host)),
+ collection_id.clone().unwrap_or("".to_string())))
+ )
+ }
+
+ iframe
+ style="display: none;"
+ srcdoc=(
+ maud::html! {
+ (maud::DOCTYPE)
+ html {
+ body {
+ form action=(PreEscaped(endpoint.to_string())) method=(method.to_string()) #payment_form {
+ @for (field, value) in form_fields {
+ input type="hidden" name=(field) value=(value);
+ }
+ }
+ (PreEscaped(format!(r#"
+ <script type="text/javascript"> {logging_template}
+ var form = document.getElementById("payment_form");
+ var formFields = form.querySelectorAll("input");
+ window.setTimeout(function () {{
+ if (form.method.toUpperCase() === "GET" && formFields.length === 0) {{
+ window.location.href = form.action;
+ }} else {{
+ form.submit();
+ }}
+ }}, 300);
+ </script>
+ "#)))
+ }
+ }
+ }.into_string()
+ )
+ {}
+ }
+ }
+ },
}
}
|
2024-10-20T09:44:04Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Described in #6177
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Integrates Worldpay's 3DS flow
## How did you test it?
Things to test
1. 3DS payments using automatic capture
2. No 3DS payment using manual capture (full amount captures)
3. Payments Sync
<details>
<summary>1. Create and capture</summary>
cURL
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \
--data-raw '{"authentication_type":"three_ds","capture_method":"automatic","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"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":"en-US","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":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}'
Response
{"payment_id":"pay_OjJGWEhFHNpycXbZmDNS","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_OjJGWEhFHNpycXbZmDNS_secret_vMQEnVxtwo0xKYXtDTqh","created":"2024-10-21T10:59:11.767Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@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":"1091","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"400000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"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":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_OjJGWEhFHNpycXbZmDNS/merchant_1728979001/pay_OjJGWEhFHNpycXbZmDNS_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508351,"expires":1729511951,"secret":"epk_dfac7bbac2014a18ae323ba08bfe7e9b"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoibVJjNnpNRE45cys3RmIxWjRRbWF2SWd4akc2VC9KdHZiVlgrTTRvTURQdzJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"3fbccf2f-0ab5-494c-9909-1c8d2be40049","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:45:51.767Z","fingerprint":null,"browser_info":{"language":"en-US","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-21T10:59:12.308Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
Open the link and continue
https://github.com/user-attachments/assets/52239cd6-fa40-45e3-88a9-231115ab8b20
</details>
<details>
<summary>2. Create a payment using manual capture</summary>
cURL
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \
--data-raw '{"authentication_type":"three_ds","capture_method":"manual","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","profile_id":"pro_OodaMoJ1Y9nlnegU4soR","amount":100,"currency":"USD","confirm":true,"connector":["worldpay"],"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"john.doe@example.com","session_expiry":10000,"return_url":"https://example.com","off_session":true,"payment_method":"card","payment_method_type":"credit","payment_method_data":{"card":{"card_number":"4000000000001091","card_exp_month":"12","card_exp_year":"2030","card_holder_name":"John Doe","card_cvc":"123"}},"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":"en-US","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":"John","statement_descriptor_suffix":"JD","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"}}'
Response
{"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@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":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"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":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":{"type":"redirect_to_url","redirect_to_url":"http://localhost:8080/payments/redirect/pay_ff5lUcN6X1lg5f2PBtyv/merchant_1728979001/pay_ff5lUcN6X1lg5f2PBtyv_1"},"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"cus_sH6s3hf1uukqvYlAGkj5","created_at":1729508611,"expires":1729512211,"secret":"epk_739c58c7f7384fac89c7099e1cdae436"},"manual_retry_allowed":null,"connector_transaction_id":"eyJrIjoxLCJkIjoiQTRKMWZFZXlONnFqdGhHTWlmWDdYY2RzUVlIUzI2dEdLcEFPak9GRzNaczJJRGpBeDR3ekZaWWVqNDJzOTJkWiJ9","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"5b1cdf1c-26ea-42b1-b6e0-a02453ebf21f","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","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-21T11:03:31.677Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
cURL (capture)
curl --location --request POST 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9' \
--data '{}'
Response
{"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@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":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"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":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"f7cb203a-aa4d-4fbc-84e7-9f6c1a9273a5","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","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-21T11:04:47.760Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
</details>
<details>
<summary>3. Payments Sync</summary>
cURL
curl --location --request GET 'http://localhost:8080/payments/pay_ff5lUcN6X1lg5f2PBtyv?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_sMl3D9efytjSoXznSOKCv5PHyql50M1BMhU8e7qsa5m6mXxHvyROVg7cER7AWue9'
Response
{"payment_id":"pay_ff5lUcN6X1lg5f2PBtyv","merchant_id":"merchant_1728979001","status":"processing","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"worldpay","client_secret":"pay_ff5lUcN6X1lg5f2PBtyv_secret_6iktmiNQwi8DAsIRNn4i","created":"2024-10-21T11:03:31.227Z","currency":"USD","customer_id":"cus_sH6s3hf1uukqvYlAGkj5","customer":{"id":"cus_sH6s3hf1uukqvYlAGkj5","name":"John Doe","email":"john.doe@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":"manual","payment_method":"card","payment_method_data":{"card":{"last4":"1096","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"520000","card_extended_bin":null,"card_exp_month":"12","card_exp_year":"2030","card_holder_name":null,"payment_checks":null,"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":{"number":"8056594427","country_code":"+91"},"email":null},"order_details":null,"email":"john.doe@example.com","name":"John Doe","phone":"999999999","return_url":"https://example.com/","authentication_type":"three_ds","statement_descriptor_name":"John","statement_descriptor_suffix":"JD","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"credit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLZqKn+Z0amZtgDGJNxxTouoBznrTCkCd2i5TQsznCawECpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa:C6PZmXicLsKiJilUv0dIUwRuaBJaSeFhCq3fDWQC7:n7drI2adm1BXX7w39afnJw==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"eaf9a1d5-031a-4b3b-b70b-ed9b7ec05406","payment_link":null,"profile_id":"pro_OodaMoJ1Y9nlnegU4soR","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_omabWO9B7CSmaCMuT6eh","incremental_authorization_allowed":false,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-21T13:50:11.227Z","fingerprint":null,"browser_info":{"language":"en-US","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-21T11:06:18.222Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null}
</details>
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
58296ffae6ff6f2f2c8f7b23dd28e92b374b9be3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.